patternbashkubernetesTip
CronJob and Job patterns in Kubernetes
Viewed 0 times
cronjobjobbatchscheduledone-time taskbackupttlsecondsafterfinishedbackofflimitconcurrencypolicycron schedule
Problem
One-off or scheduled batch tasks (database backups, report generation, data pipelines) need to run in the cluster but Deployment is not the right abstraction — it keeps pods running continuously.
Solution
Use a Job for one-time tasks and CronJob for scheduled tasks.
# One-time Job
apiVersion: batch/v1
kind: Job
metadata:
name: db-backup
spec:
ttlSecondsAfterFinished: 3600 # auto-cleanup after 1 hour
backoffLimit: 3
template:
spec:
restartPolicy: OnFailure
containers:
- name: backup
image: backup-tool:latest
command: ["./run-backup.sh"]
---
# Scheduled CronJob
apiVersion: batch/v1
kind: CronJob
metadata:
name: nightly-report
spec:
schedule: "0 2 * * *" # 2am every day
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 1
jobTemplate:
spec:
template:
spec:
restartPolicy: OnFailure
containers:
- name: report
image: reporter:latestWhy
Jobs ensure a pod runs to successful completion (exit 0), retrying on failure up to backoffLimit. CronJobs create Jobs on a cron schedule. Neither keeps a pod running indefinitely — they are completion-oriented.
Gotchas
- restartPolicy must be OnFailure or Never for Job pods — Always is not valid
- concurrencyPolicy: Forbid prevents overlapping executions if a previous job is still running
- CronJob schedules use the cluster's timezone (usually UTC) — add timezone field in Kubernetes 1.25+ with
timeZone: America/New_York - Failed pods from Jobs linger unless ttlSecondsAfterFinished or successfulJobsHistoryLimit is set
- Manually trigger a CronJob:
kubectl create job --from=cronjob/nightly-report manual-run-1
Code Snippets
Manually trigger and monitor Kubernetes Jobs
# Manually trigger a CronJob
kubectl create job --from=cronjob/nightly-report manual-run-$(date +%s)
# Check job status
kubectl get jobs
kubectl logs job/db-backupContext
Running batch, one-off, or scheduled tasks in Kubernetes
Revisions (0)
No revisions yet.