CodeBlanks Logo Icon CodeBlanks

CronJob YAML

Learn the CronJob YAML structure.

CronJob YAML

A CronJob's spec has a schedule and a jobTemplate; the jobTemplate is identical to a Job's spec (that's why three nested specs appear):

apiVersion: batch/v1
kind: CronJob
metadata:
  name: gece-yedek
spec:
  schedule: "0 3 * * *"
  jobTemplate:
    spec:
      template:
        spec:
          restartPolicy: OnFailure
          containers:
            - name: yedek
              image: postgres:16
              command: ["sh", "-c", "pg_dump -h db -U app app > /yedek/app.sql"]

Concurrency and history

Three important settings:

  • concurrencyPolicy: Allow (default), Forbid (skip if it overlaps the previous one), Replace (stop the previous one, start the new one).
  • startingDeadlineSeconds: a missed run can still be started within this time.
  • successfulJobsHistoryLimit / failedJobsHistoryLimit: the number of old Jobs kept (default 3 / 1).
spec:
  schedule: "0 3 * * *"
  timeZone: "Europe/Istanbul"
  concurrencyPolicy: Forbid
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 5

Practice A nightly backup

Write a CronJob YAML: name gece-yedek; schedule: "0 3 * * *"; concurrencyPolicy: Forbid; restartPolicy: OnFailure in the pod template inside jobTemplate; container named yedek, image postgres:16.

Starter code

terminal
# buraya yaz

Sample solution

terminal
apiVersion: batch/v1
kind: CronJob
metadata:
  name: gece-yedek
spec:
  schedule: "0 3 * * *"
  concurrencyPolicy: Forbid
  jobTemplate:
    spec:
      template:
        spec:
          restartPolicy: OnFailure
          containers:
            - name: yedek
              image: postgres:16

Expected output

cronjob.batch/gece-yedek created

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens if the next run time arrives before the previous backup finishes?

  • Both always run together
  • The CronJob is deleted
  • It errors
  • It depends on concurrencyPolicy: Allow, Forbid or Replace Correct answer

Explanation: For jobs like backups, Forbid is chosen to prevent overlap.

2 Skip an overlapping run.

Question
spec:
  schedule: "0 3 * * *"
  concurrencyPolicy: ____
Answer
spec:
  schedule: "0 3 * * *"
  concurrencyPolicy: Forbid

Explanation: Forbid doesn't start a new one if the previous hasn't finished.

3 Match.

Term Meaning
Allow Allow overlap
Forbid Skip the overlapping one
Replace Stop the old one
timeZone Time zone

All lessons in Advanced