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
ColumnMeaning
SCHEDULECron expression
SUSPENDtrue if paused
LAST SCHEDULELast fire time

3. Describing CronJob Details

SectionInfo
Schedule / TimeZoneWhen to fire
Concurrency PolicyAllow / Forbid / Replace
ActiveCurrently running Jobs

4. Setting Schedule Expression

FieldRange
Minute0-59
Hour0-23
Day of month1-31
Month1-12
Day of week0-6 (Sun=0)

5. Understanding Cron Syntax

ExpressionMeaning
"*/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

PolicyEffect
Allow (default)Multiple Jobs can run concurrently
ForbidSkip new run if previous still active
ReplaceCancel running and start new

7. Setting Successful Jobs History

FieldDefault
successfulJobsHistoryLimit3
failedJobsHistoryLimit1

8. Setting Failed Jobs History

Note: Set higher (5-10) when debugging intermittent failures.
TipReason
IncreaseKeep evidence for postmortems
Set 0Auto-delete failed jobs

9. Suspending CronJobs

kubectl patch cj backup -p '{"spec":{"suspend":true}}'
kubectl patch cj backup -p '{"spec":{"suspend":false}}'
FieldEffect
suspend: trueSkip future runs; existing Jobs continue

10. Setting Starting Deadline

FieldEffect
startingDeadlineSecondsSkip missed run if delay exceeds N seconds
DefaultUnset = 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)
UseDetail
Ad-hoc triggerSnapshot template into immediate Job
TestingVerify changes before scheduled time

12. Deleting CronJobs

kubectl delete cj backup                # also deletes child Jobs & Pods
kubectl delete cj backup --cascade=orphan  # keep children