What is a Kubernetes CronJob?
A CronJob creates Jobs on a time-based schedule. It's an extension of the Job resource that provides a method of executing jobs on a cron-like schedule.
Time-Based Scheduling
Execute jobs on a cron-like schedule using UTC time
Job Extension
Built on top of the Job resource with scheduling capabilities
History Management
Automatic management of job history and cleanup
Important: CronJobs use UTC time only. Make sure to account for your timezone when setting schedules.
kubectl Commands for CronJobs
Imperative Creation
--image=busybox --schedule="*/1 * * * *" \
-- /bin/sh -c "date;"
The imperative way to create a CronJob
Declarative Creation
Create a CronJob using YAML configuration
List CronJobs
Get Detailed Info
Delete a CronJob
kubectl delete cj [jobName]
Two ways to delete: using the YAML file or the CronJob name
Cron Schedule Syntax
CronJobs use the standard cron format with five time fields. All times are in UTC.
Field Definitions
- Minute: 0 - 59
- Hour: 0 - 23 (24-hour format)
- Day of the month: 1 - 31
- Month: 1 - 12
- Day of the week: 0 - 6 (Sunday to Saturday; 7 is also Sunday on some systems)
Common Schedule Examples
*/5 * * * *
Every 5 minutes
0 * * * *
Every hour
0 2 * * *
Daily at 2:00 AM
0 0 * * 0
Weekly on Sunday
0 0 1 * *
Monthly on the 1st
Reference: For complete cron syntax documentation, visit Wikipedia Cron Page
Job History Management
CronJobs automatically manage the history of completed and failed jobs to prevent resource accumulation.
Default History Limits
- The last 3 successful jobs are kept
- The last 1 failed job is kept
- Setting
successfulJobsHistoryLimitto zero keeps none - Setting
failedJobsHistoryLimitto zero keeps none
Example Pod List
| NAME | READY | STATUS | RESTARTS | AGE |
|---|---|---|---|---|
| myjob-1556555640-9bc5r | 0/1 | Completed | 0 | 3m6s |
| myjob-1556555700-cm6wk | 0/1 | Completed | 0 | 2m6s |
| myjob-1556555760-62wf5 | 0/1 | Completed | 0 | 66s |
History Configuration
apiVersion: batch/v1
kind: CronJob
metadata:
name: hello
spec:
schedule: "*/1 * * * *"
successfulJobsHistoryLimit: 3 # Keep 3 successful jobs
failedJobsHistoryLimit: 1 # Keep 1 failed job
jobTemplate:
spec:
template:
spec:
containers:
- name: hello
image: busybox
command: ["/bin/sh", "-c", "date; echo Hello from Kubernetes"]
restartPolicy: OnFailure
Note: Setting history limits to zero will immediately clean up jobs after they complete. This can make debugging difficult.
Common CronJob Use Cases
Database Backups
Regular database backups and maintenance tasks
Report Generation
Daily, weekly, or monthly report generation
Cleanup Tasks
Regular cleanup of temporary files or old data
Data Synchronization
Periodic data sync between systems
Health Checks
Regular health checks and monitoring tasks
Notification Sending
Scheduled email or notification distribution