Skip to main content

Jobs & CronJobs

πŸ“˜ Know

Be able to explain it and pass its lab once. Phase 5 of the Learning Path.

Docs: Jobs Β· CronJob Β· Indexed Jobs

Overview​

A Deployment keeps Pods running forever. A Job runs Pods until a set number of them succeed, then stops. A CronJob creates a Job on a schedule. They are the same reconcile loop as every other controller (β†’ Architecture), except "done" is a reachable state. Use a Job for migrations, batch processing and one-off tasks. Use a CronJob for anything that should happen every night, hour or minute. The interview questions almost always concern failure: retries, overlapping runs and runs that never happened.

Key concepts​

Job fields​

FieldDefaultWhat it controls
completions1How many Pods must succeed
parallelism1How many Pods run at once
backoffLimit6Retries before the Job is marked Failed. Delays grow 10s, 20s, 40s… up to 6 min.
activeDeadlineSecondsnoneHard wall-clock limit for the whole Job. Beats backoffLimit.
ttlSecondsAfterFinishednoneDelete the Job and its Pods this long after it finishes
completionMode: IndexedNonIndexedEach Pod gets JOB_COMPLETION_INDEX (0…n-1) to pick its slice of work
template.spec.restartPolicy(required)OnFailure or Never. Always is rejected.

restartPolicy inside a Job​

ValueOn failureResult
OnFailureContainer restarts in the same PodFewer Pods, but the failed container's logs are replaced
NeverA new Pod is createdFailed Pods stay for kubectl logs. Use while debugging.
Always(rejected by the API)Validation error

CronJob fields​

FieldDefaultWhat it controls
schedule(required)Cron syntax: minute hour day-of-month month day-of-week
timeZonecontroller's zone, usually UTCIANA name such as Asia/Singapore
concurrencyPolicyAllowWhat happens when the previous run is still going (table below)
startingDeadlineSecondsnoneIf a run is missed by more than this, skip it
successfulJobsHistoryLimit / failedJobsHistoryLimit3 / 1How many finished Jobs to keep
suspendfalsePause scheduling without deleting the CronJob

concurrencyPolicy​

ValuePrevious run still activeResult
AllowStart another oneTwo retraining runs writing the same files. Usually a bug.
ForbidSkip this runSafe for jobs that must not overlap. A slow run means missed runs.
ReplaceKill the old run, start the new oneLatest data wins. A run that always overruns never finishes.

kubectl essentials​

Create imperatively:

kubectl create job hello --image=busybox:1.36 -- sh -c 'echo hello; sleep 5'
kubectl create cronjob report --image=busybox:1.36 --schedule="*/5 * * * *" -- date
kubectl create job report-manual --from=cronjob/report # run a CronJob now
kubectl create job hello --image=busybox:1.36 --dry-run=client -o yaml -- echo hi > job.yaml

Inspect and control:

kubectl get jobs,cronjobs
kubectl logs job/hello # logs of one of the Job's Pods
kubectl get pods -l job-name=hello # every Pod the Job created
kubectl wait --for=condition=complete job/hello --timeout=120s
kubectl patch cronjob report -p '{"spec":{"suspend":true}}'

A parallel Job with bounded retries and cleanup:

apiVersion: batch/v1
kind: Job
metadata:
name: process
spec:
completions: 5
parallelism: 2
backoffLimit: 3
activeDeadlineSeconds: 600
ttlSecondsAfterFinished: 3600
completionMode: Indexed
template:
spec:
restartPolicy: Never
containers:
- name: worker
image: busybox:1.36
command: ["sh", "-c", "echo processing shard $JOB_COMPLETION_INDEX; sleep 5"]

A nightly CronJob that must never overlap:

apiVersion: batch/v1
kind: CronJob
metadata:
name: nightly-report
spec:
schedule: "0 2 * * *"
timeZone: Asia/Singapore
concurrencyPolicy: Forbid
startingDeadlineSeconds: 1800
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 3
jobTemplate:
spec:
backoffLimit: 2
activeDeadlineSeconds: 7200
template:
spec:
restartPolicy: OnFailure
containers:
- name: report
image: busybox:1.36
command: ["sh", "-c", "echo building report; sleep 30"]

πŸ§ͺ Lab​

Lab 5-1 β˜…β˜…

Requires: Standard lab setup Β· Generate, edit, apply Β· How the tiers work.

Watch concurrencyPolicy: Forbid skip a run.

Goal

  1. In namespace lab5-1, create a CronJob slow that runs every minute, sleeps 90 seconds, and uses concurrencyPolicy: Forbid.
  2. Watch Jobs for 4 minutes. Explain why there are fewer Jobs than minutes.
  3. Trigger a manual run from the CronJob and confirm it runs even while a scheduled one is active.
  4. Suspend the CronJob.

Verify

kubectl -n lab5-1 get cronjob slow -o jsonpath='{.spec.concurrencyPolicy} {.spec.suspend}{"\n"}' # Forbid true
kubectl -n lab5-1 get jobs
🟑 Hints
  1. kubectl create cronjob -h. The generator can't set concurrencyPolicy: generate, edit, apply.
  2. kubectl get jobs -w. Compare each run's length with the schedule interval.
  3. kubectl create job -h has a --from flag.
  4. suspend is a boolean in the CronJob's spec. kubectl patch sets one field.
🟒 Guided
  1. Create the lab namespace.

    kubectl create namespace lab5-1
  2. Generate a CronJob manifest that runs every minute and sleeps 90s.

    kubectl -n lab5-1 create cronjob slow --image=busybox:1.36 --schedule="* * * * *" \
    --dry-run=client -o yaml -- sleep 90 > slow.yaml
  3. Edit slow.yaml: add concurrencyPolicy: Forbid under spec:.

  4. Create the CronJob from the edited file.

    kubectl -n lab5-1 apply -f slow.yaml
  5. Watch Jobs appear.

    kubectl -n lab5-1 get jobs -w
    NAME STATUS COMPLETIONS DURATION AGE
    slow-29841788 Complete 1/1 93s 3m20s
    slow-29841789 Complete 1/1 93s 107s
    slow-29841791 Running 0/1 14s 14s

    Three Jobs in over four minutes, never two at once. Forbid doesn't start a tick that finds a run active, but with no startingDeadlineSeconds the missed tick isn't lost either: the controller starts it late, as soon as the previous run finishes. So runs go back to back (...89 started when ...88 ended), and ticks that pile up collapse into one (...90 never ran). Set startingDeadlineSeconds if a late run is worse than no run.

  6. Start a Job from the CronJob's template right now.

    kubectl -n lab5-1 create job slow-manual --from=cronjob/slow

    Manual Jobs bypass concurrencyPolicy. That rule is the CronJob controller's, not the Job's.

  7. Pause the schedule without deleting the CronJob.

    kubectl -n lab5-1 patch cronjob slow -p '{"spec":{"suspend":true}}'
  8. Run the βœ… Check below, then delete everything the lab created.

    kubectl delete namespace lab5-1

βœ… Check

t() { [ "$2" = "$3" ] && echo "PASS $1" || echo "FAIL $1: got '$2', want '$3'"; }
t "concurrencyPolicy Forbid" "$(kubectl -n lab5-1 get cronjob slow -o jsonpath='{.spec.concurrencyPolicy}')" "Forbid"
t "suspended" "$(kubectl -n lab5-1 get cronjob slow -o jsonpath='{.spec.suspend}')" "true"
t "manual run created" "$(kubectl -n lab5-1 get job slow-manual -o jsonpath='{.metadata.name}')" "slow-manual"
t "never 2 scheduled at once" "$(kubectl -n lab5-1 get jobs -o jsonpath='{range .items[*]}{.metadata.name} {.status.active}{"\n"}{end}' | grep -v manual | grep -c ' 1$' | awk '{print ($1<=1)?"yes":"no"}')" "yes"

Gotchas​

  • Time zone. Without timeZone, 0 2 * * * means 02:00 in the controller-manager's zone, usually UTC.
  • Jobs must be idempotent. The controller can occasionally create two Jobs for one schedule, or none. Design for it.
  • Finished Jobs pile up. Standalone Jobs stay forever unless you set ttlSecondsAfterFinished.
  • OnFailure restarts count too. Container restarts inside a Pod burn backoffLimit just like failed Pods. Set activeDeadlineSeconds as the real cap.
  • Too many missed runs. If more than 100 schedules are missed (for example, after a long suspend without startingDeadlineSeconds), the CronJob stops scheduling and logs an error.
  • Editing a CronJob doesn't touch running Jobs. Only the next Job uses the new template.

Scenario questions​

Q1 β˜… A Job has created a string of failed Pods and stopped. What happened and what do you check?

Model answer
  • Clarify: did it ever succeed? Is this a new image or new input data?
  • Observe: kubectl describe job shows BackoffLimitExceeded. kubectl logs on the newest failed Pod shows the error. restartPolicy: Never kept each failed Pod, one per attempt.
  • Hypothesise: the task fails deterministically: a bad argument, a missing Secret, or bad data.
  • Fix: fix the cause, delete the Job, re-create it. A failed Job does not retry on its own.
  • Prevent: lower backoffLimit for deterministic failures and alert on Job failure. Use podFailurePolicy to fail fast on exit codes that retries can't fix.

Q2 β˜…β˜… The nightly job sometimes runs twice at once and corrupts its output. How do you stop that?

Model answer
  • Clarify: how long does a run take compared to the schedule interval? Does it ever run long?
  • Observe: kubectl get jobs shows two active Jobs with overlapping start times. concurrencyPolicy is Allow, the default.
  • Hypothesise: a slow night pushed a run past the next schedule, and Allow started a second one.
  • Fix: set concurrencyPolicy: Forbid and activeDeadlineSeconds so a hung run can't block every later one.
  • Prevent: make the job idempotent anyway (write to a temp path, then rename), because the controller doesn't strictly guarantee one run per schedule. The trade-off: Forbid means a slow run skips the next one, so alert on missed runs.

Q3 β˜…β˜… The CronJob didn't run last night. Where do you look?

Model answer
  • Clarify: didn't run at all, or ran and failed?
  • Observe: kubectl get cronjob for SUSPEND and LAST SCHEDULE. kubectl describe cronjob for events such as missed schedules. kubectl get jobs for a failed Job.
  • Hypothesise: suspended; the previous run still active under Forbid; the start was later than startingDeadlineSeconds because the control plane was down; or the schedule is in UTC while you expected local time.
  • Fix: resume it, set timeZone, or trigger a catch-up with kubectl create job --from=cronjob/<name>.
  • Prevent: alert when the last successful run is older than the interval, a "dead man's switch".

Q4 β˜…β˜…β˜… You must process 1,000 files as fast as possible without a message queue. Design it.

Model answer
  • Clarify: are files independent? How long does one take? What limits parallelism: cluster capacity or a downstream API?
  • Observe: independent files and a fixed list make static partitioning possible.
  • Hypothesise: an Indexed Job with completions: 100 and parallelism: 20. Each Pod reads JOB_COMPLETION_INDEX and processes files index*10 to index*10+9.
  • Fix: set backoffLimitPerIndex so one bad shard retries alone and doesn't fail the whole Job. Size parallelism to what the downstream can take, not the cluster.
  • Prevent: trade-off vs a queue: indexed Jobs are simple and need no infrastructure, but work is split up front. If items vary wildly in cost, a work queue balances load better.

Summary​

  • Jobs run to completion; Deployments run forever. Pick by whether "done" exists.
  • backoffLimit retries, activeDeadlineSeconds caps. Set both.
  • concurrencyPolicy: Forbid stops overlapping runs. The cost is skipped runs when one is slow.
  • Always set timeZone and ttlSecondsAfterFinished. UTC surprises and piles of finished Jobs are the two classic messes.
  • Make every Job idempotent. Retries and the occasional double run are part of the contract.

Next in path β†’ Storage