The Kubernetes CronJob
docs mention that a CronJob
supports the use case of:
- Once at a specified point in time
But, I don't see any examples/documentation of how this would be possible. Specifically, I'm looking to kick off a job to run once in N hours. Is this supported in any version of Kubernetes?
According to documentation, CronJob uses the common Cron format of schedule:
Here are some examples:
schedule: "1 2-14 * * 0-1,5-6" (first minute of every hour from 2am to 2pm UTC on Sun,Mon,Fri,Sat)
schedule: "*/1 * * * *" (every minute)
CronJobs also have some limitations:
A cron job creates a job object about once per execution time of its schedule. We say “about” because there are certain circumstances where two jobs might be created, or no job might be created. We attempt to make these rare, but do not completely prevent them. Therefore, jobs should be idempotent.
If
startingDeadlineSeconds
is set to a large value or left unset (the default) and ifconcurrencyPolicy
is set toAllow
, the jobs will always run at least once.Jobs may fail to run if the CronJob controller is not running or broken for a span of time from before the start time of the CronJob to start time plus
startingDeadlineSeconds
, or if the span covers multiple start times andconcurrencyPolicy
does not allow concurrency. For example, suppose a cron job is set to start at exactly08:30:00
and itsstartingDeadlineSeconds
is set to10
, if the CronJob controller happens to be down from08:29:00
to08:42:00
, the job will not start. Set a longerstartingDeadlineSeconds
if starting later is better than not starting at all.The Cronjob is only responsible for creating Jobs that match its schedule, and the Job in turn is responsible for the management of the Pods it represents.
The other important thing is that Kubernetes uses UTC exclusively. Make sure you take that into account when you’re creating your schedule.
To run a job just once, you can use kubectl create -f job.yaml
started by at command on the admin machine or on the master node.
echo "kubectl create -f job.yaml" | at midnight
It is just as a regular CronJob object but using a format for the cronjob expression to run at a specific point in time:
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: my-cronjob
namespace: kube-system
spec:
schedule: "7 7 7 7 6"
restartPolicy: OnFailure
jobTemplate:
...
for example this will run “At 07:07, Saturday 7th of July 2018.”
Next occurrence will be in 2029 so you have plenty of time to delete the cronJob object. That is, it will create a new job if you don't delete it as far and as I am aware there are no ways to avoid this.