Skip to content
LF Cert Trainer

Lesson 62 · Section 5: Application Lifecycle Management

Lesson 62: CronJobs: Jobs on a schedule

How a CronJob creates a Job at each scheduled time, how to read the cron syntax and time zones, what concurrencyPolicy, startingDeadlineSeconds, suspend and the history limits do, and how to create, test and debug a CronJob quickly in the exam. · 16 min read · 3 min video

1/8CronJobs
0:00 / 2:36

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

Why CronJobs exist

The previous lesson's Job runs a task once, when you create it. Much operational work is not once but again and again, at fixed times: a database dump every night, a report every Monday, a cache clean-up every fifteen minutes. On a single Linux server you would put a line in a crontab. In a cluster there is no single server to put it on, and the work should survive a node going down.

A CronJob is the Kubernetes version of a crontab line. It holds a schedule and a Job template, and at each scheduled time it creates a new Job from that template.

CronJob, Job, Podcreatescreatesnightly-backupCronJob, 0 2 * * *Job ...-29421240yesterday, CompleteJob ...-29422680today, RunningPod ...680-k8x2dRunningNext Jobtomorrow 02:00
CronJob, Job, Pod. A CronJob does not run containers. At each scheduled time it creates a Job from its jobTemplate, and the Job creates the Pods. Old Jobs are deleted when there are more than the history limits allow.

Parts:

  • nightly-backup (CronJob, 0 2 * * *)
  • Job ...-29421240 (yesterday, Complete)
  • Job ...-29422680 (today, Running)
  • Pod ...680-k8x2d (Running)
  • Next Job (tomorrow 02:00)

Connections:

  • nightly-backup to Job ...-29421240
  • nightly-backup to Job ...-29422680: creates
  • Job ...-29422680 to Pod ...680-k8x2d: creates
  • nightly-backup to Next Job

What a CronJob is made of

apiVersion: batch/v1
kind: CronJob
metadata:
  name: nightly-backup
spec:
  schedule: "0 2 * * *"              # when: 02:00 every day
  timeZone: "Europe/Bucharest"       # optional: in which time zone
  concurrencyPolicy: Forbid          # what to do if the last run is still going
  startingDeadlineSeconds: 600       # a run may start at most 10 minutes late
  successfulJobsHistoryLimit: 3      # keep the last 3 successful Jobs
  failedJobsHistoryLimit: 1          # keep the last failed Job
  jobTemplate:                       # a Job spec: everything from the Jobs lesson
    spec:
      backoffLimit: 2
      template:                      # a Pod template
        spec:
          restartPolicy: OnFailure
          containers:
            - name: backup
              image: busybox:1.36
              command: ["sh", "-c", "date; echo backing up"]

Three levels are nested here, and each level has its own fields:

LevelPathFields that belong here
CronJobspecschedule, timeZone, concurrencyPolicy, startingDeadlineSeconds, suspend, the history limits
Jobspec.jobTemplate.speccompletions, parallelism, backoffLimit, activeDeadlineSeconds, ttlSecondsAfterFinished
Podspec.jobTemplate.spec.template.specrestartPolicy, containers, volumes, everything a Pod has

All CronJob fields at a glance:

FieldDefaultMeaning
schedulerequiredFive cron fields, or a macro such as @hourly
timeZonethe time zone of kube-controller-managerAn IANA name such as Etc/UTC or America/New_York
concurrencyPolicyAllowAllow, Forbid or Replace for overlapping runs
startingDeadlineSecondsnoneHow late a missed run may still start; later runs are skipped
suspendfalsetrue stops new runs; running Jobs continue
successfulJobsHistoryLimit3Finished successful Jobs to keep
failedJobsHistoryLimit1Failed Jobs to keep

The schedule

The schedule is standard cron syntax: five fields separated by spaces.

┌───────────── minute        (0-59)
│ ┌─────────── hour          (0-23)
│ │ ┌───────── day of month  (1-31)
│ │ │ ┌─────── month         (1-12, or JAN-DEC)
│ │ │ │ ┌───── day of week   (0-6, Sunday = 0, or SUN-SAT)
│ │ │ │ │
0 2 * * *
SymbolMeaningExampleReads as
*Every value* * * * *Every minute
,A list0 8,20 * * *08:00 and 20:00
-A range0 9 * * 1-509:00 on weekdays
/A step*/15 * * * *Every 15 minutes
macroA shortcut@hourly, @daily (also @midnight), @weekly, @monthly, @yearly@daily is 0 0 * * *

The shortest unit is one minute; there is no seconds field. A sixth field, as some other cron tools accept, makes the schedule invalid.

Time zones

Without timeZone, the schedule is read in the local time zone of the kube-controller-manager process. On a kubeadm cluster that runs in a container that is almost always UTC, so 0 2 * * * means 02:00 UTC. To run at 02:00 local time, set the field:

spec:
  schedule: "0 2 * * *"
  timeZone: "Europe/Bucharest"

The value must be a name from the IANA time zone database. Writing the zone into the schedule itself, as in CRON_TZ=UTC 0 2 * * *, is rejected by the API server; use the field.

How it works: the CronJob controller

The CronJob controller in kube-controller-manager checks every CronJob regularly. For each one it works out the most recent scheduled time that has passed and whether a Job exists for it.

  1. Find the latest scheduled time that has passed
  2. A Job for that time exists? Nothing to do
  3. Suspended, or too late (startingDeadlineSeconds)? Skip it
  4. Last Job still running? Apply concurrencyPolicy
  5. Create the Job from jobTemplate
  6. Delete Jobs beyond the history limits
One check of the CronJob controller

Each Job's name is the CronJob's name plus a number: the scheduled time in minutes since 1970 (nightly-backup-29422680). Because the name comes from the time, the controller can never create two Jobs for the same scheduled time, even if it restarts in the middle. It is also why a CronJob name may be at most 52 characters: the suffix needs the remaining 11 of the 63 allowed.

The Job carries an owner reference to its CronJob, so deleting the CronJob deletes its Jobs, and with them their Pods. The Job's labels and annotations come from jobTemplate.metadata.

Late and missed runs

A run can be late: the controller manager was down, the control plane was being upgraded, or the CronJob was suspended. What happens when it can act again depends on startingDeadlineSeconds:

SettingA run that is late...
Not setStarts as soon as the controller sees it (only the most recent missed time, not each one)
startingDeadlineSeconds: 600Starts if it is at most 10 minutes late, otherwise it is skipped and counted as missed
Under the hood · The 100 missed schedules rule

The controller counts how many scheduled times were missed since the last run (or, with startingDeadlineSeconds, within that window). If the count is above 100, it does not start a Job and records the event Cannot determine if job needs to be started. Too many missed start times (> 100). With a schedule of every minute, that happens after the controller has been down for just under two hours.

Setting startingDeadlineSeconds keeps the count small, because only the misses inside the window are counted. That is one more reason to set it on frequent CronJobs. Resuming a CronJob that was suspended a long time ago has the same effect: without a deadline, it would count every scheduled time of the pause.

Overlapping runs: concurrencyPolicy

The previous run is still going: concurrencyPolicyScheduled timelast Job still runningAllow (default)two Jobs runForbidthis run is skippedReplaceold Job deleted
The previous run is still going: concurrencyPolicy. When a scheduled time comes and the last Job has not finished, the policy decides. Allow starts another Job next to it, Forbid skips this run, Replace deletes the running Job and starts a new one.

Parts:

  • Scheduled time (last Job still running)
  • Allow (default) (two Jobs run)
  • Forbid (this run is skipped)
  • Replace (old Job deleted)

Connections:

  • Scheduled time to Allow (default)
  • Scheduled time to Forbid
  • Scheduled time to Replace

A backup scheduled every hour that one day takes ninety minutes is still running when the next hour comes. The policy decides what happens:

PolicyAt the next scheduled timeGood for
Allow (default)A second Job starts next to the firstIndependent runs, such as sending a report
ForbidThe new run is skipped; the next one is at the following scheduled timeWork that must not overlap, such as a backup of the same database
ReplaceThe running Job is deleted, then the new one startsWork where only the latest run matters, such as refreshing a cache

The policy only compares Jobs of the same CronJob. Two different CronJobs do not know about each other.

Suspending and resuming

spec.suspend: true stops the CronJob from creating new Jobs. Jobs that are already running continue, and nothing is deleted.

kubectl patch cronjob nightly-backup -p '{"spec":{"suspend":true}}'
kubectl get cronjob nightly-backup                 # SUSPEND True
kubectl patch cronjob nightly-backup -p '{"spec":{"suspend":false}}'

Runs that fell into the pause count as missed. When you resume, at most the most recent one is started late (or none, if it is older than startingDeadlineSeconds).

Changing a CronJob

Unlike a Job, a CronJob can be edited. kubectl edit cronjob or kubectl apply with a new schedule or image is fine. The change applies to the next Job it creates; Jobs that already exist keep the template they were made from. kubectl set image cronjob/nightly-backup backup=busybox:1.37 works too.

CronJob or something else?

You wantUse
A task at fixed times, repeatedlyCronJob
A task once, nowJob
A loop that checks something every few secondsA Deployment whose container sleeps between checks; a CronJob's minimum is one minute, and starting a Pod per run costs seconds
A task once at a single future timeA CronJob with that date, suspended or deleted afterwards; Kubernetes has no "at" command

Using it

Example · Create a CronJob that runs every five minutes

The task: "create a CronJob cleanup in namespace ops that runs busybox:1.36 with echo cleaning every five minutes, keeps only 2 successful Jobs and never runs two at once".

kubectl -n ops create cronjob cleanup --image=busybox:1.36 --schedule='*/5 * * * *' \
  --dry-run=client -o yaml -- echo cleaning > cleanup.yaml

Add two lines under spec, next to schedule:

spec:
  schedule: '*/5 * * * *'
  concurrencyPolicy: Forbid
  successfulJobsHistoryLimit: 2
  jobTemplate:
    ...
kubectl apply -f cleanup.yaml
kubectl -n ops get cronjob cleanup

kubectl create cronjob writes restartPolicy: OnFailure into the Pod template. That is fine unless the task asks for something else.

Example · Test it now instead of in five minutes

kubectl -n ops create job cleanup-test --from=cronjob/cleanup
kubectl -n ops wait --for=condition=complete job/cleanup-test --timeout=60s
kubectl -n ops logs job/cleanup-test          # cleaning
kubectl -n ops delete job cleanup-test

The Job is made from the CronJob's current jobTemplate, so this tests exactly what the schedule will run.

Example · A CronJob that never seems to run

kubectl get cronjob report shows LAST SCHEDULE <none> long after it should have run.

kubectl get cronjob report -o jsonpath='{.spec.schedule} {.spec.timeZone} {.spec.suspend}{"\n"}'
kubectl describe cronjob report | tail -n 15        # events: created Jobs, missed runs, errors
kubectl get jobs --sort-by=.metadata.creationTimestamp | tail -n 3

Work through the usual causes: the CronJob is suspended; the schedule is right but in UTC while you expected local time; the day fields mean something else than intended (0 0 * 12 * is every day of December, not 12 days from now); concurrencyPolicy: Forbid and a previous Job that never ends (ACTIVE 1 for hours); or the Jobs are created but their Pods fail, which is a Job problem, not a CronJob problem.

Example · Read the output of the last run

kubectl get jobs -l app=report --sort-by=.metadata.creationTimestamp   # if jobTemplate.metadata set that label
kubectl get jobs --sort-by=.metadata.creationTimestamp | grep report   # otherwise by name
kubectl logs job/report-29422680

Only as many Jobs as the history limits allow are kept. If the run you need is gone, raise successfulJobsHistoryLimit (or failedJobsHistoryLimit) and wait for the next one.

Tricks

Common mistakes

  • Unquoted schedules. The shell or the YAML parser eats the *.
  • Six fields. There is no seconds field; five fields or a macro only.
  • Fields at the wrong level. backoffLimit under spec instead of spec.jobTemplate.spec, or restartPolicy anywhere but the Pod template.
  • Expecting local time. Without timeZone the schedule is in the controller manager's time zone, usually UTC.
  • Thinking Forbid queues the run. It skips it; the next run is at the next scheduled time.
  • Editing a CronJob to fix a running Job. Edits only affect Jobs created afterwards.
  • Looking for the Job of last week. By default only 3 successful Jobs and 1 failed Job are kept.

Recap

  • A CronJob creates a Job from jobTemplate at each time in schedule; the Job creates the Pods. Job fields go in jobTemplate.spec, Pod fields in jobTemplate.spec.template.spec.
  • The schedule has five fields (minute, hour, day of month, month, day of week) or a macro, read in timeZone or, by default, the controller manager's time zone.
  • concurrencyPolicy: Allow (default), Forbid (skip) or Replace (delete the running Job). startingDeadlineSeconds limits how late a run may start; suspend pauses new runs.
  • Only 3 successful and 1 failed Job are kept by default. Job names end in the scheduled time in minutes.
  • In the exam: kubectl create cronjob NAME --image=IMG --schedule='...' -- CMD, then test with kubectl create job NAME --from=cronjob/NAME.

Official docs

Quiz: check what you learned

6 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

A hands-on lab for this lesson. You get goals, not steps: any solution that reaches them passes.

  • Repair a CronJob: its schedule and time zone, overlapping runs, history limits and a job template that fails.

    Fix · Level 2 · standard · target 20 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.