Jobs and CronJobs — Running Tasks
A Job creates one or more pods and ensures that a specified number of them successfully terminate. When a Job completes, the pods are not restarted.
A CronJob creates Jobs on a repeating schedule — like a cron job on a Linux system.
Jobs
apiVersion: batch/v1
kind: Job
metadata:
name: pi
spec:
completions: 1
parallelism: 1
template:
spec:
containers:
- name: pi
image: perl
command: ["perl", "-Mbignum=bpi", "-wle", "print bpi(2000)"]
restartPolicy: Never
backoffLimit: 4
completions — How many pods need to successfully finish.
parallelism — How many pods can run at the same time.
backoffLimit — How many times to retry before marking the Job as failed.
restartPolicy: Never — Failed pods are not restarted; new ones are created instead.
CronJobs
apiVersion: batch/v1
kind: CronJob
metadata:
name: database-backup
spec:
schedule: "0 2 * * *" # Every day at 2 AM
jobTemplate:
spec:
template:
spec:
containers:
- name: backup
image: my-backup-image
command: ["/bin/sh", "-c", "backup-script.sh"]
restartPolicy: OnFailure
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 1
schedule — Standard cron format: minute, hour, day, month, weekday.
successfulJobsHistoryLimit — How many completed Jobs to keep for debugging.
failedJobsHistoryLimit — How many failed Jobs to keep.
Managing Jobs and CronJobs
# Run a Job
kubectl apply -f job.yaml
# Check Job status
kubectl get jobs
kubectl describe job pi
# View pod logs
kubectl logs job/pi
# Create a CronJob
kubectl apply -f cronjob.yaml
# Manually trigger a CronJob (bypass the schedule)
kubectl create job manual-backup --from=cronjob/database-backup
# Delete a CronJob
kubectl delete cronjob database-backup
Common Use Cases
Database backups — Run a backup script every night.
Data processing — Process a batch of records and terminate.
Report generation — Generate PDF reports on a schedule.
Cleanup tasks — Remove old logs or temporary files periodically.