What is a CronJob?
- Docker & Kubernetes course
- Advanced
- Lesson 28/70
- 4 min
Learn scheduled tasks with a CronJob.
What is a CronJob?
A CronJob creates Jobs on a schedule: nightly backups, hourly reports, weekly cleanup. The schedule is in Unix cron format: minute hour day-of-month month day-of-week:
"0 3 * * *" every day at 03:00
"*/15 * * * *" every 15 minutes
"0 9 * * 1" every Monday at 09:00
"0 0 1 * *" midnight on the 1st of every monthThe time zone defaults to the kube-controller-manager's (usually UTC); it can be changed with timeZone: "Europe/Istanbul".
Managing a CronJob
A CronJob can also be created with a command. To trigger it by hand without waiting for the next run, a Job is produced from it; to pause it temporarily, suspend is used:
kubectl create cronjob temizlik --image=busybox:1.36 --schedule="0 4 * * *" -- sh -c "echo temizlendi"
kubectl create job temizlik-elle --from=cronjob/temizlik
kubectl patch cronjob temizlik -p '{"spec":{"suspend":true}}'
kubectl get cronjobsPractice A scheduled cleanup
Write three commands: create a CronJob temizlik with the busybox:1.36 image running echo temizlendi every day at 04:00 ("0 4 * * *"); produce a Job temizlik-elle from it by hand; list the CronJobs.
Starter code
# buraya yazSample solution
kubectl create cronjob temizlik --image=busybox:1.36 --schedule="0 4 * * *" -- echo temizlendi
kubectl create job temizlik-elle --from=cronjob/temizlik
kubectl get cronjobsExpected output
cronjob.batch/temizlik created job.batch/temizlik-elle created NAME SCHEDULE TIMEZONE SUSPEND ACTIVE LAST SCHEDULE AGE temizlik 0 4 * * * <none> False 0 <none> 5s
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does the schedule "30 2 * * 0" run?
- Every Sunday at 02:30 Correct answer
- Every day at 02:30
- On the 30th of every month
- Every 30 minutes
Explanation: Day of week 0 is Sunday.
2 Produce a Job from a CronJob by hand.
kubectl create job temizlik-elle ____=cronjob/temizlik
kubectl create job temizlik-elle --from=cronjob/temizlik
Explanation: --from=cronjob/name creates a Job from the template.
3 Match the schedules.
| Term | Meaning |
|---|---|
0 3 * * * |
Every day 03:00 |
*/15 * * * * |
Every 15 minutes |
0 9 * * 1 |
Monday 09:00 |
0 0 1 * * |
The 1st at 00:00 |