Kubernetes CronJob: Scheduled Tasks in Your Cluster

A Kubernetes CronJob is like a recurring alarm for your cluster. It automatically runs tasks like backups or reports on a schedule, creating a new Job for each run. The main footgun is concurrency: by default, jobs can overlap if one runs too long.
WHY IT EXISTS: To run recurring, automated tasks directly within a Kubernetes cluster. Instead of relying on an external system like a Jenkins server or a system cron daemon to trigger work, CronJobs provide a native way to handle scheduled operations like backups and reports.
THE MENTAL MODEL: Think of a CronJob as a recurring calendar event for Kubernetes. You don't create the task each time; you define a template for the task (the Job) and a schedule (the cron expression). The Kubernetes control plane acts as the assistant that checks the calendar and launches the task at the specified time.
HOW IT WORKS: A CronJob resource contains two key parts: a schedule in standard cron format (e.g., 0 5 * * 1 for 5 AM every Monday) and a jobTemplate. At the scheduled time, the CronJob controller creates a Job resource from this template. The Job then creates one or more Pods to execute the containerized task. The CronJob also manages the lifecycle of old Jobs, retaining a configurable number of successful and failed runs for auditing (successfulJobsHistoryLimit and failedJobsHistoryLimit).
WHEN TO USE IT: Use CronJobs for any time-based, repetitive task. Common use cases include: first, running nightly database backups; second, generating and emailing weekly performance reports; third, performing hourly cleanup of temporary files or database records.
WHEN NOT TO USE IT: Don't use a CronJob for long-running services that should always be available; use a Deployment for that. For a one-off task that doesn't repeat, use a simple Job instead. CronJobs are also not suitable for tasks requiring high-precision timing, as there can be slight delays in scheduling.
ONE CANONICAL EXAMPLE: A daily database backup. A CronJob is configured with the schedule 0 2 * * * to run at 2 AM every day. The jobTemplate specifies a container with database client tools. When triggered, the Job starts a Pod that executes a script to dump the database, compress it, and upload it to cloud storage. The concurrencyPolicy is set to Forbid to prevent a new backup from starting if the previous day's is still running, a common and critical configuration.
Read the original → kubernetes.io
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.