Sign In

Curriculum 18: Jobs & CronJobs

CronJobs

15 min · 25 XP

CronJobs

A CronJob creates Jobs on a repeating schedule, similar to the Unix cron utility. CronJobs are ideal for periodic tasks like database backups, report generation, and cleanup scripts.

CronJob Definition

apiVersion: batch/v1
kind: CronJob
metadata:
  name: db-backup
spec:
  schedule: "0 2 * * *"
  concurrencyPolicy: Forbid
  suspend: false
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 1
  jobTemplate:
    spec:
      template:
        spec:
          restartPolicy: OnFailure
          containers:
            - name: backup
              image: postgres:16
              command: ["pg_dump", "-h", "db-host", "-U", "admin", "mydb"]
kubectl apply -f cronjob.yaml
kubectl get cronjobs

Cron Schedule Syntax

The schedule field uses standard cron format with five fields:

# minute  hour  day-of-month  month  day-of-week
  0       2     *             *      *          # Daily at 2:00 AM
  */15    *     *             *      *          # Every 15 minutes
  0       9     *             *      1-5        # Weekdays at 9:00 AM
  0       0     1             *      *          # First day of each month

Concurrency Policy

The concurrencyPolicy field controls overlapping Jobs:

  • Allow (default) -- permits concurrent Jobs
  • Forbid -- skips the new run if the previous one is still active
  • Replace -- cancels the running Job and starts a new one

Suspending a CronJob

# Pause scheduled runs
kubectl patch cronjob db-backup -p '{"spec":{"suspend":true}}'

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

Triggering a Manual Run

kubectl create job manual-backup --from=cronjob/db-backup

This creates an immediate Job from the CronJob template without waiting for the next scheduled run.