What Is a CronJob in Kubernetes?

beginner|jobsdevopssrebackend developerCKACKAD
TL;DR

A CronJob creates Jobs on a recurring schedule using standard cron syntax. It is the Kubernetes equivalent of a Linux cron task, used for periodic batch work like backups, report generation, and cleanup scripts.

Detailed Answer

A CronJob is a Kubernetes object that creates Jobs on a time-based schedule. It works like a Linux crontab but runs in the cluster, managed by the Kubernetes control plane.

Basic CronJob Example

apiVersion: batch/v1
kind: CronJob
metadata:
  name: daily-backup
spec:
  schedule: "0 2 * * *"    # Every day at 2:00 AM
  jobTemplate:
    spec:
      template:
        spec:
          containers:
            - name: backup
              image: myapp/backup:v1.5
              command: ["./backup.sh"]
              env:
                - name: S3_BUCKET
                  value: "my-backups"
                - name: DB_CONNECTION
                  valueFrom:
                    secretKeyRef:
                      name: db-credentials
                      key: connection-string
              resources:
                requests:
                  cpu: "500m"
                  memory: "512Mi"
                limits:
                  cpu: "2"
                  memory: "2Gi"
          restartPolicy: OnFailure
      backoffLimit: 3
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 1

Cron Schedule Syntax

The schedule field uses standard cron format:

┌───────────── minute (0 - 59)
│ ┌───────────── hour (0 - 23)
│ │ ┌───────────── day of month (1 - 31)
│ │ │ ┌───────────── month (1 - 12)
│ │ │ │ ┌───────────── day of week (0 - 6, Sunday = 0)
│ │ │ │ │
* * * * *

Common examples:

| Schedule | Meaning | |---|---| | */5 * * * * | Every 5 minutes | | 0 * * * * | Every hour | | 0 2 * * * | Daily at 2:00 AM | | 0 0 * * 0 | Weekly on Sunday at midnight | | 0 0 1 * * | Monthly on the 1st at midnight | | 0 9 * * 1-5 | Weekdays at 9:00 AM |

Concurrency Policy

The concurrencyPolicy controls what happens when a new scheduled run overlaps with a still-running Job:

spec:
  schedule: "*/10 * * * *"
  concurrencyPolicy: Forbid    # Skip if previous Job is still running

| Policy | Behavior | |---|---| | Allow (default) | Multiple Jobs can run simultaneously | | Forbid | Skip the new Job if the previous one is still running | | Replace | Terminate the running Job and start a new one |

Best practice: Use Forbid for tasks that should not overlap (like database backups) and Allow only when concurrent runs are safe.

Handling Missed Schedules

If the CronJob controller is down or the cluster is under heavy load, scheduled Jobs may be missed. The startingDeadlineSeconds field controls the grace period:

spec:
  schedule: "0 2 * * *"
  startingDeadlineSeconds: 600    # 10-minute window

If the scheduled time passes and more than 600 seconds elapse, the Job is skipped. Without this field, Kubernetes attempts to catch up on missed runs (up to 100 missed schedules).

Suspending a CronJob

You can temporarily disable a CronJob without deleting it:

# Suspend the CronJob
kubectl patch cronjob daily-backup -p '{"spec":{"suspend":true}}'

# Resume it
kubectl patch cronjob daily-backup -p '{"spec":{"suspend":false}}'

Suspended CronJobs do not create new Jobs, and any missed runs during suspension are not caught up.

History Limits

CronJobs accumulate completed Jobs over time. Control cleanup with:

spec:
  successfulJobsHistoryLimit: 3    # Keep last 3 successful Jobs (default)
  failedJobsHistoryLimit: 1        # Keep last 1 failed Job (default)

Set these based on your debugging needs. Failed Jobs should be retained longer for investigation.

Monitoring CronJobs

# List CronJobs with schedule and status
kubectl get cronjobs
# NAME           SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
# daily-backup   0 2 * * *     False     0        12h             30d

# See Jobs created by a CronJob
kubectl get jobs -l job-name=daily-backup

# Manually trigger a CronJob for testing
kubectl create job --from=cronjob/daily-backup manual-backup-test

The kubectl create job --from=cronjob command is invaluable for testing — it creates a one-off Job from the CronJob template without waiting for the schedule.

Why Interviewers Ask This

Interviewers ask this to verify you know how to handle scheduled tasks in Kubernetes instead of relying on node-level cron or external schedulers.

Common Follow-Up Questions

What happens if a CronJob's previous run is still active when the next one is scheduled?
This depends on the concurrencyPolicy: Allow (default) creates the new Job alongside the running one, Forbid skips the new run, and Replace terminates the current Job and starts a new one.
What is the startingDeadlineSeconds field?
It defines a grace period in seconds. If the CronJob misses its scheduled time by more than this window (due to controller downtime), the Job is not created.
How many Job history records does a CronJob keep?
By default, 3 successful Jobs (successfulJobsHistoryLimit) and 1 failed Job (failedJobsHistoryLimit). Older records are cleaned up.

Key Takeaways

  • CronJobs automate Job creation on a schedule using cron syntax.
  • The concurrencyPolicy field prevents overlapping runs for long-running tasks.
  • CronJobs automatically clean up old Job records based on history limits.

Related Questions

You Might Also Like