Working with CronJobs
1. Creating CronJob
Example: Nightly backup
apiVersion: batch/v1
kind: CronJob
metadata: { name: backup }
spec:
schedule: "0 2 * * *" # 02:00 daily
timeZone: "UTC"
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 5
startingDeadlineSeconds: 600
jobTemplate:
spec:
backoffLimit: 2
template:
spec:
restartPolicy: OnFailure
containers:
- name: dump
image: postgres:16
command: ["sh","-c","pg_dump -h db -U app app | gzip > /backup/$(date +%F).sql.gz"]
2. Listing CronJobs
kubectl get cj
kubectl get cj -A
kubectl get jobs -l owner=cronjob-backup
| Column | Meaning |
| SCHEDULE | Cron expression |
| SUSPEND | true if paused |
| LAST SCHEDULE | Last fire time |
3. Describing CronJob Details
| Section | Info |
| Schedule / TimeZone | When to fire |
| Concurrency Policy | Allow / Forbid / Replace |
| Active | Currently running Jobs |
4. Setting Schedule Expression
| Field | Range |
| Minute | 0-59 |
| Hour | 0-23 |
| Day of month | 1-31 |
| Month | 1-12 |
| Day of week | 0-6 (Sun=0) |
5. Understanding Cron Syntax
| Expression | Meaning |
"*/5 * * * *" | Every 5 minutes |
"0 */2 * * *" | Every 2 hours |
"0 9-17 * * 1-5" | Hourly weekdays 9-17 |
"@hourly" | Nickname (0 * * * *) |
"@daily" | 0 0 * * * |
"@weekly" | 0 0 * * 0 |
6. Configuring Concurrency Policy
| Policy | Effect |
| Allow (default) | Multiple Jobs can run concurrently |
| Forbid | Skip new run if previous still active |
| Replace | Cancel running and start new |
7. Setting Successful Jobs History
| Field | Default |
| successfulJobsHistoryLimit | 3 |
| failedJobsHistoryLimit | 1 |
8. Setting Failed Jobs History
Note: Set higher (5-10) when debugging intermittent failures.
| Tip | Reason |
| Increase | Keep evidence for postmortems |
| Set 0 | Auto-delete failed jobs |
9. Suspending CronJobs
kubectl patch cj backup -p '{"spec":{"suspend":true}}'
kubectl patch cj backup -p '{"spec":{"suspend":false}}'
| Field | Effect |
| suspend: true | Skip future runs; existing Jobs continue |
10. Setting Starting Deadline
| Field | Effect |
| startingDeadlineSeconds | Skip missed run if delay exceeds N seconds |
| Default | Unset = always run when scheduler notices |
Warning: Without deadline, CronJob may fire 100+ missed runs after a long control-plane outage.
11. Creating Manual Job Run
kubectl create job --from=cronjob/backup backup-manual-$(date +%s)
| Use | Detail |
| Ad-hoc trigger | Snapshot template into immediate Job |
| Testing | Verify changes before scheduled time |
12. Deleting CronJobs
kubectl delete cj backup # also deletes child Jobs & Pods
kubectl delete cj backup --cascade=orphan # keep children