The cron scheduler in Kubernetes works very similarly to that of a typical Linux system. This should make it a bit easier for seasoned Linux users that have done their share of crontab editing in the past. However, there is still a specific way to create cron jobs in Kubernetes and a syntax that your YAML file must follow.
In this tutorial, we will see how to create a cron job in Kubernetes. This is a handy feature that allows us to schedule and automate tasks at certain intervals or future dates. Those already familiar with Linux crontab will have an advantage since they already know the general syntax of a cron command. Let’s see how to schedule jobs in Kubernetes.
In this tutorial you will learn:
- How to create a cron job YAML file
- How to schedule a cron job in Kubernetes
- How to check on cron jobs in Kubernetes
|Category||Requirements, Conventions or Software Version Used|
|System||Any Linux distro|
|Other||Privileged access to your Linux system as root or via the
# – requires given linux commands to be executed with root privileges either directly as a root user or by use of
$ – requires given linux commands to be executed as a regular non-privileged user
Create a cron job in Kubernetes
These steps assume that you already have your Kubernetes cluster up and running, and have access to the kubectl command.
- Cron jobs are managed by the Kubernetes control plane. We can program a new job to run by applying a YAML file. An example syntax looks like the following:
apiVersion: batch/v1 kind: CronJob metadata: name: hello-world spec: schedule: "* * * * *" jobTemplate: spec: template: spec: containers: - name: hello image: busybox:1.28 imagePullPolicy: IfNotPresent command: - /bin/sh - -c - date; echo Hello Kubernetes! restartPolicy: OnFailure
See our crontab reference guide for help with the scheduling syntax of cron, such as by minute, hour, day, etc. Crontab guru is also a handy way to quickly get the needed syntax for a specific time interval.
- Then, run the new cron job with the
$ kubectl create -f ./cronjob.yaml cronjob.batch/hello-world created
- See the cronjob by executing:
$ kubectl get cronjob hello-world
- To see the cron jobs being executed in real time, use the following command:
$ kubectl get jobs --watch
- We can also view the pods which have been spawned to execute the cron job:
$ kubectl get pods
- We can see the results of the cron job (in our case, just echoed text) by inspecting the logs for one of the pods:
$ kubectl logs hello-world-27982521-bgb46
- To delete the cron job, use the
$ kubectl delete cronjob hello-world
In this tutorial, we saw how to create a cron job for Kubernetes on a Linux system. As seen here, the process is not very different from creating an ordinary cron job on Linux, with the only difference being the YAML file and the
kubectlcommand. Kubernetes even gives us an easy way to check on all of our cron jobs and see the results after they have been executed.