What is a CronJob in Kubernetes?

If you’ve ever used Linux, you probably know cron – a tool to schedule recurring tasks. Kubernetes has a similar concept called CronJob.

A CronJob in Kubernetes is a resource that allows you to run jobs on a schedule, like database backups, sending reports, or periodic cleanup tasks.


How CronJobs Work

  • A Job in Kubernetes runs a task once and then exits.
  • A CronJob is a Job with a schedule, defined in cron format (* * * * *).

Every time the schedule is triggered, Kubernetes creates a new Job pod.


Example: Simple CronJob

Here’s a CronJob that prints “Hello Kubernetes” every minute:

apiVersion: batch/v1
kind: CronJob
metadata:
  name: hello-cron
spec:
  schedule: "*/1 * * * *"   # every 1 minute
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: hello
            image: busybox
            args:
            - /bin/sh
            - -c
            - "echo Hello Kubernetes! $(date)"
          restartPolicy: OnFailure

Common Use Cases

  • Database backups (e.g., dump PostgreSQL/MySQL daily).
  • Log rotation or cleanup of old files.
  • Automated reports (export metrics, send email).
  • Health checks or periodic pings to external services.

Things to Watch Out For

  • Missed schedules: if the cluster is down, missed jobs won’t rerun by default.
  • Too frequent schedules: could overload the cluster.
  • Always set successfulJobsHistoryLimit and failedJobsHistoryLimit to avoid pod clutter.

Conclusion

CronJobs bring cron-like automation to Kubernetes. They are perfect for repeating tasks like backups, cleanups, and scheduled reports. Use them wisely, and don’t forget to monitor your jobs!