Geavanceerd
Zoeken inHow-to-gidsen
Zo zoek je
  • Typ de taak in je eigen woorden (poort vinden, firewall openen, schijf vol) of plak een foutmelding tussen aanhalingstekens.
  • Kies "Snel antwoord" om alleen de commando's te zien, of een gebied om in één vakgebied te blijven.
  • "twee woorden" vindt precies die zin.
  • Gewone woorden vinden namen, teksten en voorbeelden.
  • ↑ ↓ bewegen · Enter openen · Esc sluiten · / zoeken
Probeer:

How-to 134Kubernetes · Workloads

How to run a scheduled job with a CronJob

Nightly reports, cleanups, database dumps, certificate checks — in Kubernetes these run as a CronJob: on a schedule, Kubernetes creates a Job, the Job runs a Pod until it finishes. This how-to writes a safe CronJob (no overlapping runs, time zone, retries, history), runs it once by hand to test, and finds out why a run failed.

  • 5 Lessen
  • 3 Commando's

Dit deel is nog niet vertaald. Je ziet de Engelse tekst.

$ als gewone gebruiker# als root (of met sudo)

134.1

The quick answer

cronjob.yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: nightly-report
  namespace: shop
spec:
  schedule: "15 2 * * *"
  timeZone: "Asia/Riyadh"
  concurrencyPolicy: Forbid
  startingDeadlineSeconds: 600
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 5
  jobTemplate:
    spec:
      backoffLimit: 2
      activeDeadlineSeconds: 3600
      template:
        spec:
          restartPolicy: Never
          containers:
            - name: report
              image: registry.example.com/shop/jobs:1.4.2
              args: ["python", "-m", "jobs.nightly_report"]
              envFrom:
                - secretRef: { name: db-cred }
kubectl apply -f cronjob.yaml
kubectl create job --from=cronjob/nightly-report report-test -n shop
kubectl logs -n shop job/report-test -f

134.2

Step by step

  1. Schedule — the same 5 fields as cron. timeZone (Kubernetes 1.27+) avoids UTC surprises.
  2. The safety settings:
SettingWhy
concurrencyPolicy: ForbidNever two runs at the same time (a slow run skips the next).
startingDeadlineSecondsSkip a run that could not start within this time (no burst of late runs).
backoffLimit: 2Retry a failed Pod twice, then mark the Job failed.
activeDeadlineSecondsKill a run that hangs.
restartPolicy: NeverA failed Pod stays for its logs (a new Pod is used for the retry).
*JobsHistoryLimitKeep some old Jobs for logs, delete the rest.
  1. Test it now — create a Job from the CronJob (quick answer) instead of waiting for 02:15.
  2. See the runs:
kubectl get cronjob nightly-report -n shop
NAME             SCHEDULE     TIMEZONE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
nightly-report   15 2 * * *   Asia/Riyadh   False     0        6h              9d
kubectl get jobs -n shop --sort-by=.metadata.creationTimestamp | tail -5
kubectl logs -n shop job/nightly-report-29384715
  1. Pause during maintenance:
kubectl patch cronjob nightly-report -n shop -p '{"spec":{"suspend":true}}'
  1. Alert on failures — a failed Job is easy to miss. With Prometheus/kube-state-metrics alert on kube_job_status_failed > 0, or let the job ping a dead-man's switch (Uptime Kuma push monitor) when it succeeds.

134.3

Check that it worked

The manual test Job completes (COMPLETIONS 1/1), its log shows the work, LAST SCHEDULE updates each night, and old Jobs are cleaned up by the history limits.

134.4

Common problems

ProblemCauseFix
Runs at the wrong hourSchedule is UTC without timeZone.Set timeZone, or convert the time.
Two runs at once, data brokenconcurrencyPolicy: Allow (default).Forbid (or Replace).
Cannot determine if job needs to be started: too many missed start timesController was down / suspended long.startingDeadlineSeconds; it recovers by itself.
Job never finishesThe process does not exit, or waits for input.activeDeadlineSeconds; make the command exit.
No logs of a failed runPods deleted (history 0, or OnFailure restarts).Keep failedJobsHistoryLimit; restartPolicy: Never.
Nobody noticed it failed for weeksNo alert.Alert on failed Jobs or a missing success ping.

134.5

Go further

1Which setting stops two runs of a CronJob from running at the same time?

concurrencyPolicy: Forbid.

2How do you run a CronJob once now to test it?

Alle commando's in dit hoofdstuk