Jobs and CronJobs

Jobs and CronJobs

Deployments keep things running. Jobs make things finish.

Job

Runs Pods until the required number succeed.

apiVersion: batch/v1
kind: Job
metadata:
  name: pi
spec:
  completions: 3            # successful Pods needed
  parallelism: 2            # at most 2 at a time
  backoffLimit: 4           # retries before the Job fails
  activeDeadlineSeconds: 120
  ttlSecondsAfterFinished: 600   # auto-delete when done
  template:
    spec:
      restartPolicy: Never  # or OnFailure - never Always
      containers:
        - name: pi
          image: perl:5.40
          command: ["perl", "-Mbignum=bpi", "-wle", "print bpi(200)"]
FieldEffect
completions / parallelismhow many, how many at once
backoffLimitfailed attempts before Failed (exponential back-off)
activeDeadlineSecondshard time limit for the whole Job
ttlSecondsAfterFinishedgarbage-collect the Job and its Pods

CronJob

Creates a Job on a schedule.

graph LR CJ["CronJob<br/>*/5 * * * *"] -->|every 5 min| J1[Job] CJ --> J2[Job] J1 --> P1[Pod] J2 --> P2[Pod]
apiVersion: batch/v1
kind: CronJob
metadata:
  name: report
spec:
  schedule: "0 2 * * *"            # 02:00 every day
  timeZone: "Europe/Prague"
  concurrencyPolicy: Forbid        # Allow | Forbid | Replace
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 1
  jobTemplate:
    spec:
      template:
        spec:
          restartPolicy: OnFailure
          containers:
            - name: report
              image: busybox:1.36
              command: ["sh", "-c", "date; echo report done"]
kubectl create job test --from=cronjob/report     # run it now
kubectl patch cronjob report -p '{"spec":{"suspend":true}}'

References