Kubernetes Tutorial · Workloads · Lesson 12 of 26
Jobs and CronJobs
Run batch work to completion, retry on failure, and schedule recurring tasks.
Jobs
A Job runs pods until a number of them complete successfully. Useful fields: backoffLimit (retries),
completions and parallelism, activeDeadlineSeconds, and ttlSecondsAfterFinished to clean up.
CronJobs
A CronJob creates a Job on a schedule ("0 3 * * *", with an optional timeZone). Set
concurrencyPolicy: Forbid when runs must not overlap, and make jobs idempotent: a job can run twice
(retries, missed schedules).
kubectl create namespace demo-jobs > /dev/null
trap 'kubectl delete namespace demo-jobs --wait=false > /dev/null' EXIT
cat > job.yaml <<'EOF'
apiVersion: batch/v1
kind: Job
metadata:
name: report
spec:
completions: 3
parallelism: 3
backoffLimit: 2
template:
spec:
restartPolicy: Never
containers:
- name: worker
image: busybox:1.37
command: ["sh", "-c", "echo processed shard $JOB_COMPLETION_INDEX"]
completionMode: Indexed
EOF
kubectl -n demo-jobs apply -f job.yaml > /dev/null
kubectl -n demo-jobs wait --for=condition=Complete job/report --timeout=120s > /dev/null
kubectl -n demo-jobs get job report -o custom-columns=SUCCEEDED:.status.succeeded,FAILED:.status.failed
for i in 0 1 2; do kubectl -n demo-jobs logs "$(kubectl -n demo-jobs get pods -l batch.kubernetes.io/job-completion-index=$i -o name)"; done
kubectl -n demo-jobs create cronjob nightly --image=busybox:1.37 --schedule="0 3 * * *" -- echo cleanup > /dev/null
kubectl -n demo-jobs get cronjob nightly -o custom-columns=SCHEDULE:.spec.schedule,SUSPENDED:.spec.suspend,CONCURRENCY:.spec.concurrencyPolicy
Output
SUCCEEDED FAILED 3 <none> processed shard 0 processed shard 1 processed shard 2 SCHEDULE SUSPENDED CONCURRENCY 0 3 * * * false Allow
Run this on your computer — see “Get Started” for setup.
Test yourself
Why must CronJob workloads be idempotent?
CronJobs run in parallel alwaysA scheduled job can run more than once (retries, missed schedules), so repeating it must be safeKubernetes requires it syntacticallyTo save CPU
Show answer
Answer: A scheduled job can run more than once (retries, missed schedules), so repeating it must be safe
Design jobs so a second run causes no harm.