Jobs & Cronjobs
Job is a Kubernetes object that executes a workload and then terminates once the workload is complete. When a
Job finishes, the containers involved are terminated and the
Pod transitions to the Completed state.
Pods are similar in that they’re both used to run containers. However,
Pods typically run containers continuously, whereas
Jobs run containers to do a discrete piece of work and then terminate.
Job below is taken from the Kubernetes documentation and uses Perl to compute π to 2000 decimal places.
- name: pi
command: ["perl", "-Mbignum=bpi", "-wle", "print bpi(2000)"]
When we create this
Job, the container runs for 9 seconds and then terminates.
We can see the script output by viewing the
Pod logs for this
CronJob is a Kubernetes object that executes a workload on a schedule. A
CronJob is an extension of a
Job but rather than running once and terminating, a
CronJob runs according to a schedule specified in the manifest. The following
CronJob definition runs a container that prints the current date/time and the text CronJob running!!. The
schedule attribute specifies how often the workload should run. In this case,
*/1 * * * * tells Kubernetes to run the workload very minute.
schedule: "*/1 * * * *" #run every minute
spec: # Job Spec
template: # Pod Template
spec: # Pod Spec
- name: cron-container
command: ['sh', '-c', 'date; echo CronJob running!!']
After creating the definition above we can list the
CronJob and the
Pods that it has created. As you can see from the screenshot, a new
Pod is created every minute.
The sample code for these notes is available on Github.