What is a Kubernetes CronJob?
Making Jobs run on a schedule.
A CronJob is a Kubernetes object that creates Jobs on a schedule. If a job is a task that runs once, a CronJob is the same task running repeatedly at a defined time, much like the cron utility on Linux.
This is useful for recurring tasks: nightly data processing, scheduled backups, periodic report generation, and so on.
apiVersion: batch/v1kind: CronJobmetadata: name: nightly-backupspec: schedule: '0 2 * * *' jobTemplate: spec: completions: 1 parallelism: 1 template: spec: containers: - name: backup image: my-app:1.0 command: ['python', 'backup.py'] restartPolicy: NeverLet’s break this YAML down:
- schedule uses standard cron syntax (minute, hour, day of month, month, day of week). The example above runs at 2am every day;
- jobTemplate is the Job template that the CronJob creates on each scheduled run. It has the same structure as a regular job manifest (completions, parallelism, pod template, and so on).
The schedule field follows the standard five-field cron format:
| Field | Allowed values |
|---|---|
| Minute | 0-59 |
| Hour | 0-23 |
| Day of month | 1-31 |
| Month | 1-12 |
| Day of week | 0-6 (Sun=0) |
A few common examples:
"*/5 * * * *": every 5 minutes;"0 9 * * 1-5": at 9am, Monday to Friday;"0 0 1 * *": at midnight on the first of every month.
CronJobs offer a few settings to control what happens when multiple scheduled runs overlap:
- concurrencyPolicy: decides what to do if a new job is created while the previous one is still running.
Allow(default) lets them run in parallel.Forbidskips the new run.Cancelterminates the currently running job before starting the new one; - successfulJobsHistoryLimit: how many completed jobs to keep in the cluster (default is 3);
- failedJobsHistoryLimit: how many failed jobs to keep (default is 1).
A CronJob creates jobs based on the configured schedule. However, if the Kubernetes controller manager is down or the cluster is under heavy load, a run might be missed. Kubernetes does not go back and run missed schedules; it simply waits for the next one.