Jobs & Cronjobs
Jobs
A 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.
Jobs
and 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.
The sample Job
below is taken from the Kubernetes documentation and uses Perl to compute π to 2000 decimal places.
apiVersion: batch/v1 kind: Job metadata: name: pi spec: template: spec: containers: - name: pi image: perl command: ["perl", "-Mbignum=bpi", "-wle", "print bpi(2000)"] restartPolicy: Never backoffLimit: 4
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 Job
.
CronJobs
A 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.
apiVersion: batch/v1beta1 kind: CronJob metadata: name: cronjob-sample spec: schedule: "*/1 * * * *" #run every minute jobTemplate: spec: # Job Spec template: # Pod Template spec: # Pod Spec containers: - name: cron-container image: busybox command: ['sh', '-c', 'date; echo CronJob running!!'] restartPolicy: OnFailure
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.
Leave A Comment