TExcelTAD
Home › Kubernetes › Jobs & CronJobs

Jobs & CronJobs

Deployments run forever. Some work should run to completion: a database migration, a report, a batch of images to resize. A Job creates Pods until a given number of them succeed, then stops. A CronJob creates Jobs on a schedule.

A Job

yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: resize-images
spec:
  completions: 6          # need 6 successful Pods in total
  parallelism: 2          # run up to 2 at a time
  backoffLimit: 4         # allow 4 retries: the 5th failed Pod fails the Job
  activeDeadlineSeconds: 900
  ttlSecondsAfterFinished: 3600   # delete the Job an hour after it finishes
  template:
    spec:
      restartPolicy: Never        # Jobs need Never or OnFailure
      containers:
        - name: resize
          image: ghcr.io/acme/resizer:1.2
          args: ["--batch-size=100"]
bash
kubectl apply -f resize-job.yaml
kubectl get jobs -w
kubectl logs job/resize-images

Sample output:

text
NAME            STATUS     COMPLETIONS   DURATION   AGE
resize-images   Running    2/6           24s        24s
resize-images   Running    4/6           47s        47s
resize-images   Complete   6/6           71s        71s

Completions, parallelism and retries

The Job controller keeps up to parallelism Pods running until completions Pods have succeeded. Failed Pods are replaced, and the Job fails once the number of failed Pods exceeds backoffLimit (so backoffLimit: 0 means no retries at all). This model processes Pods in "waves"; the outcomes of each Pod are pre-decided so the run is repeatable:

python · try it yourself
def run_job(completions, parallelism, backoff_limit, outcomes):
    outcomes = iter(outcomes)
    succeeded = failed = wave = 0
    while succeeded < completions:
        wave += 1
        batch = min(parallelism, completions - succeeded)
        results = [next(outcomes) for _ in range(batch)]
        succeeded += results.count("ok")
        failed += results.count("fail")
        print(f"wave {wave}: started {batch} -> {results}  succeeded={succeeded} failed={failed}")
        if failed > backoff_limit:
            return "Failed (BackoffLimitExceeded)"
    return "Complete"

print(run_job(6, 2, 4, ["ok", "ok", "fail", "ok", "ok", "ok", "ok"]))
print()
print(run_job(3, 3, 2, ["ok", "fail", "fail", "fail", "ok"]))
wave 1: started 2 -> ['ok', 'ok']  succeeded=2 failed=0
wave 2: started 2 -> ['fail', 'ok']  succeeded=3 failed=1
wave 3: started 2 -> ['ok', 'ok']  succeeded=5 failed=1
wave 4: started 1 -> ['ok']  succeeded=6 failed=1
Complete

wave 1: started 3 -> ['ok', 'fail', 'fail']  succeeded=1 failed=2
wave 2: started 2 -> ['fail', 'ok']  succeeded=2 failed=3
Failed (BackoffLimitExceeded)

The real controller also waits between retries (exponential back-off of 10 s, 20 s, 40 s… capped at 6 minutes).

Patterns for splitting work:

Pattern Settings Each Pod…
Single run completions: 1 (default) does all the work
Fixed count completions: N, parallelism: M processes one unit
Indexed completionMode: Indexed gets JOB_COMPLETION_INDEX = 0…N-1 and processes "its" shard
Work queue parallelism: M, no completions pulls items from a queue until it's empty

With an Indexed Job, each Pod can compute its own slice of the input:

python · try it yourself
files = [f"img-{n:03d}.png" for n in range(1, 11)]
completions = 3

for index in range(completions):          # JOB_COMPLETION_INDEX in each Pod
    mine = files[index::completions]
    print(f"pod index {index}: {mine}")
pod index 0: ['img-001.png', 'img-004.png', 'img-007.png', 'img-010.png']
pod index 1: ['img-002.png', 'img-005.png', 'img-008.png']
pod index 2: ['img-003.png', 'img-006.png', 'img-009.png']

CronJobs

yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: nightly-report
spec:
  schedule: "30 2 * * 1-5"       # 02:30 Monday to Friday
  timeZone: "Europe/Berlin"
  concurrencyPolicy: Forbid      # Allow | Forbid | Replace
  startingDeadlineSeconds: 300
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 1
  jobTemplate:
    spec:
      backoffLimit: 2
      template:
        spec:
          restartPolicy: OnFailure
          containers:
            - name: report
              image: ghcr.io/acme/report:1.4

The schedule uses the classic five cron fields: minute hour day-of-month month day-of-week (0 = Sunday). * means every value, a-b a range, a,b a list and */n every n-th. A small expander shows which times a schedule fires during a given week:

python · try it yourself
from datetime import datetime, timedelta

def parse_field(field, lo, hi):
    values = set()
    for part in field.split(","):
        step = 1
        if "/" in part:
            part, step = part.split("/")
            step = int(step)
        if part == "*":
            start, end = lo, hi
        elif "-" in part:
            start, end = map(int, part.split("-"))
        else:
            start = end = int(part)
        values.update(range(start, end + 1, step))
    return values

def fire_times(schedule, start, days):
    minute, hour, dom, month, dow = schedule.split()
    m, h = parse_field(minute, 0, 59), parse_field(hour, 0, 23)
    dm, mo, dw = parse_field(dom, 1, 31), parse_field(month, 1, 12), parse_field(dow, 0, 6)
    t, end, out = start, start + timedelta(days=days), []
    while t < end:
        cron_dow = (t.weekday() + 1) % 7          # Python: Monday=0; cron: Sunday=0
        if t.minute in m and t.hour in h and t.day in dm and t.month in mo and cron_dow in dw:
            out.append(t.strftime("%a %Y-%m-%d %H:%M"))
        t += timedelta(minutes=1)
    return out

week = datetime(2026, 3, 1)       # Sunday, 1 March 2026
for schedule in ["30 2 * * 1-5", "0 */6 * * 0", "15 9 1,15 * *"]:
    times = fire_times(schedule, week, 7)
    print(f"{schedule!r}: {len(times)} run(s)")
    for t in times:
        print("   ", t)
'30 2 * * 1-5': 5 run(s)
    Mon 2026-03-02 02:30
    Tue 2026-03-03 02:30
    Wed 2026-03-04 02:30
    Thu 2026-03-05 02:30
    Fri 2026-03-06 02:30
'0 */6 * * 0': 4 run(s)
    Sun 2026-03-01 00:00
    Sun 2026-03-01 06:00
    Sun 2026-03-01 12:00
    Sun 2026-03-01 18:00
'15 9 1,15 * *': 1 run(s)
    Sun 2026-03-01 09:15

("15 9 1,15 * *" fires on the 1st and 15th of each month; only 1 March falls in that week.)

Warning: When both day-of-month and day-of-week are restricted (neither is *), standard cron fires when either matches, not both. Our model ANDs them, so avoid relying on that combination.

concurrencyPolicy decides what happens if the previous run is still going when the next one is due: Allow runs both, Forbid skips the new run, Replace kills the old one and starts the new one.

bash
kubectl create job --from=cronjob/nightly-report manual-run-1   # trigger a run now
kubectl get cronjob nightly-report

Test yourself

Which restartPolicy values are allowed in a Job's Pod template?

  1. Always only
  2. Never or OnFailure
  3. Any
  4. None, it is ignored

completions: 6, parallelism: 2 means…

  1. 6 Pods at once, 2 must succeed
  2. Up to 2 Pods at a time until 6 have succeeded
  3. 2 Jobs of 6 Pods
  4. Retry 6 times

What does the cron schedule 0 */6 * * 0 mean?

  1. Every 6 minutes
  2. Every 6 hours on Sundays, on the hour
  3. At 06:00 every day
  4. Once a week at midnight