⏰ CronJobs = Scheduled Tasks
Regular tasks need automation. CronJobs schedule tasks in Kubernetes. Backups, cleanup, reports — automatic.
📝 CronJob Setup
apiVersion: batch/v1
kind: CronJob
metadata:
name: daily-backup
spec:
schedule: "0 2 * * *" # Daily at 2 AM
jobTemplate:
spec:
template:
spec:
containers:
- name: backup
image: alpine:latest
command:
- /bin/sh
- -c
- |
echo "Running backup at $(date)"
# Backup command here
restartPolicy: OnFailure
# Cron Schedule Format
# ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12)
# │ │ │ │ ┌───────────── day of week (0 - 6)
# │ │ │ │ │
# * * * * *
# CronJob Examples
# Daily backup with retention
apiVersion: batch/v1
kind: CronJob
metadata:
name: db-backup
spec:
schedule: "0 3 * * *"
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 3
jobTemplate:
spec:
template:
spec:
containers:
- name: backup
image: postgres:15
command:
- /bin/sh
- -c
- |
pg_dump -h postgres-service -U postgres -d mydb > /backup/backup.sql
gzip /backup/backup.sql
restartPolicy: OnFailure
# Cleanup job (weekly)
apiVersion: batch/v1
kind: CronJob
metadata:
name: clean-temp
spec:
schedule: "0 4 * * 0" # Sunday at 4 AM
jobTemplate:
spec:
template:
spec:
containers:
- name: cleaner
image: busybox
command:
- /bin/sh
- -c
- |
echo "Cleaning temp files..."
rm -rf /tmp/*
restartPolicy: OnFailure
# CronJob Tips
- Set appropriate schedule
- Limit successful/failed history
- Monitor job completion
- Log job outputs
- Handle failures gracefully
💡 CronJob Tips
- Set appropriate schedule
- Limit successful/failed history
- Monitor job completion
- Log job outputs
- Handle failures gracefully
“CronJobs automate scheduled tasks. Backups, cleanup, reports. Essential for operations.”
