Jobs and CronJobs
- Version
- 1.37
- Since
- 1.21
- Review
- Draft
Summary#
A Job runs Pods until enough of them finish successfully, retrying failures up to backoffLimit. A CronJob creates Jobs on a cron schedule. concurrencyPolicy controls overlapping runs of that CronJob.
Syntax#
kubectl create job NAME --image=IMAGE -- COMMAND
kubectl create job NAME --from=cronjob/CRONJOB
spec:
schedule: "0 2 * * *"
timeZone: "Etc/UTC"
concurrencyPolicy: Forbid
jobTemplate:
spec:
backoffLimit: 2
Example#
The CronJob is suspended, so it creates no scheduled Jobs. The script runs a standalone Job and starts a second one from the CronJob's template.
(
set -eu
ns="ref-jobs-$$"
kubectl create namespace "$ns" >/dev/null
trap 'kubectl delete namespace "$ns" >/dev/null' EXIT
kubectl wait -n "$ns" --for=create serviceaccount/default --timeout=60s >/dev/null
kubectl apply -n "$ns" -f - <<'EOF'
apiVersion: batch/v1
kind: Job
metadata:
name: once
spec:
backoffLimit: 2
template:
spec:
restartPolicy: Never
containers:
- name: task
image: busybox:1.37
command: ["echo", "one-off task done"]
---
apiVersion: batch/v1
kind: CronJob
metadata:
name: nightly
spec:
schedule: "0 2 * * *"
timeZone: "Etc/UTC"
suspend: true
concurrencyPolicy: Forbid
jobTemplate:
spec:
backoffLimit: 2
template:
spec:
restartPolicy: Never
containers:
- name: report
image: busybox:1.37
command: ["echo", "nightly report done"]
EOF
kubectl wait -n "$ns" --for=condition=Complete job/once --timeout=120s >/dev/null
kubectl logs -n "$ns" job/once
kubectl get -n "$ns" job once -o jsonpath='succeeded={.status.succeeded}{"\n"}'
kubectl get -n "$ns" cronjob nightly -o custom-columns='SCHEDULE:.spec.schedule,TIMEZONE:.spec.timeZone,SUSPEND:.spec.suspend'
kubectl create job -n "$ns" nightly-manual --from=cronjob/nightly
kubectl wait -n "$ns" --for=condition=Complete job/nightly-manual --timeout=120s >/dev/null
kubectl logs -n "$ns" job/nightly-manual
)
Expected output#
job.batch/once created
cronjob.batch/nightly created
one-off task done
succeeded=1
SCHEDULE TIMEZONE SUSPEND
0 2 * * * Etc/UTC true
job.batch/nightly-manual created
nightly report done
Common mistakes#
Do not assume that a scheduled run happens exactly once. A CronJob can occasionally create two Jobs or none for a scheduled time, so make the task idempotent. A Job's Pod template also accepts only restartPolicy: Never or OnFailure.
Version applicability#
The batch/v1 CronJob API is available since Kubernetes 1.21; the batch/v1beta1 version is no longer served since 1.25. This lower bound concerns CronJob, because Jobs are older. The timeZone field is stable since 1.27, and the example targets 1.37.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0