Jobs & CronJobs

A Job runs a task to completion; a CronJob runs Jobs on a repeating schedule.

Syntaxschedule: "minute hour day-of-month month day-of-week"

Not every workload runs forever. Batch tasks β€” a data import, a backup, a report β€” should run once and finish. Kubernetes has two objects for this.

Jobs

A Job runs one or more Pods until a specified number succeed, then stops. If a Pod fails, the Job retries it (up to backoffLimit times). Set completions and parallelism to run many at once.

CronJobs

A CronJob creates Jobs on a schedule using standard cron syntax. Perfect for nightly backups or hourly cleanups.

FieldMeaning
* * * * *minute, hour, day-of-month, month, day-of-week
0 2 * * *every day at 02:00
*/15 * * * *every 15 minutes

Example

Example Β· yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: nightly-backup
spec:
  schedule: "0 2 * * *"
  jobTemplate:
    spec:
      template:
        spec:
          restartPolicy: OnFailure
          containers:
            - name: backup
              image: myorg/backup-tool:1.0
              args: ["--target", "s3://my-bucket/db"]

When to use it

  • A data team uses a Job to run a one-off database migration script after deploying a new application version.
  • A SaaS platform runs a nightly CronJob to generate and email usage reports to each tenant automatically.
  • A CI pipeline creates a Job to run the full integration test suite against a staging environment after every merge to main.

More examples

One-off Job manifest

Defines a Job that runs a migration script once; on failure the pod restarts, on success the Job is marked Complete.

Example Β· yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: db-migration
spec:
  template:
    spec:
      containers:
        - name: migrate
          image: myapp-migrations:1.0
          command: ["./migrate.sh"]
      restartPolicy: OnFailure

CronJob for nightly reports

Schedules a report-generator container to run daily at 2 AM using standard cron syntax.

Example Β· yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: nightly-report
spec:
  schedule: "0 2 * * *"  # 2 AM every day
  jobTemplate:
    spec:
      template:
        spec:
          containers:
            - name: reporter
              image: report-generator:1.0
          restartPolicy: OnFailure

Monitor Job completion

Checks job completion status, reads logs from the Job's pod, then cleans up the completed Job resource.

Example Β· bash
kubectl get jobs
# NAME           COMPLETIONS   DURATION   AGE
# db-migration   1/1           12s        2m

kubectl logs job/db-migration
kubectl delete job db-migration

Discussion

  • Be the first to comment on this lesson.
Jobs & CronJobs β€” Kubernetes | SoundsCode