๐ How to Schedule Tasks in Kubernetes Using CronJob
In Kubernetes, CronJobs allow you to run tasks on a recurring schedule, similar to how traditional cron jobs work in Unix-like systems. Whether it's database cleanup, sending reports, or any routine task, Kubernetes can automate it for you!
Today, I'll walk you through setting up a basic Kubernetes CronJob that runs a task every day at midnight. ๐
๐ ๏ธ YAML Example: Basic Kubernetes CronJob
Here's a simple CronJob YAML configuration that prints the current date and a message every day at midnight.
apiVersion: batch/v1
kind: CronJob
metadata:
name: example-cronjob
spec:
schedule: "0 0 * * *" # This runs the job every day at midnight
jobTemplate:
spec:
template:
spec:
containers:
- name: example
image: busybox
args:
- /bin/sh
- -c
- date; echo "Hello from the Kubernetes CronJob"
restartPolicy: OnFailure
๐ Let's break it down:
-
apiVersion: We use
batch/v1for CronJobs, specifying that this resource is a scheduled batch job. -
kind: Declares that this is a
CronJob. -
metadata.name: The name of your CronJob. In our example, it's called
example-cronjob. -
spec.schedule: The schedule for the CronJob using a cron expression.
"0 0 * * *"runs the job at midnight every day. -
jobTemplate.spec.template.spec: This section defines what the job will actually do. In this example, we use a lightweight
busyboxcontainer to print the date and a simple message. -
restartPolicy: Set to
OnFailure, meaning the job will only restart if it fails.
๐ What Can I Achieve with CronJobs?
You can use CronJobs for various tasks:
-
Daily database backups ๐๏ธ
-
Regular reporting tasks ๐
-
Automating cleanup jobs ๐งน
๐ผ๏ธ Add a Screenshot Pause:
Be sure to take screenshots of the YAML file in action! Here's how you can test it:
- Create the CronJob:
kubectl apply -f cronjob.yaml
- Check the status:
kubectl get cronjob
- View the logs of completed jobs:
kubectl get jobs
kubectl logs
This way, you can validate whether your CronJob is running correctly.
๐ Connect with me for more Kubernetes tips:
-
๐ผ LinkedIn: https://www.linkedin.com/in/rifaterdemsahin/
-
๐ฆ Twitter: https://x.com/rifaterdemsahin
-
๐ฅ YouTube: https://www.youtube.com/@RifatErdemSahin
-
๐ป GitHub: https://github.com/rifaterdemsahin
Happy coding! ๐ป๐
Imported from rifaterdemsahin.com ยท 2025