How to make cron job start after x seconds?

1.8k views Asked by At

I think I am misunderstanding Kubernetes CronJobs. On the CKAD exam there was a question to have a CronJob run every minute, but it should start after an arbitrary amount of time. I don't see any properties for CronJobs or Jobs to have them start after a specific time. Should that be part of the cron string or am I completely misunderstanding?

4

There are 4 answers

0
ahmedabouhamed On

maybe you misunderstood the question, it was to terminate the job if it didn't complete in x seconds. you should use the .spec.activeDeadlineSeconds to satisfy the requirment.

0
Brandon Kauffman On

you could do

sleep "seconds"; echo " * * * * * command" >> path/to/crontab

I feel like maybe the question is worded incorrectly. It probably meant something like every minute on every Saturday day.

 * * * * SAT

Or every minute through range of hours

* 9-17 * * *

https://crontab.guru/examples.html

0
stemixrf On

You could do something like

@reboot sleep 60 && script.sh

though you don't mention boot time specifically. You can also add sleep to the crontab.

Another way is to create a systemd service (note: on systems with systemd installed)

[Unit]
Description=cronjob with delay
After=(some criteria)

[Service]
Type=oneshot
ExecStart=/pathto/script.sh

[Install]
WantedBy=
0
Wytrzymały Wiktor On

You can schedule your CronJob to start at specific date/time and than run every minute or however you would like to set it. There is a powerful online tool that can help you with it. For example:

0 0/10 10/1 ? * * *

will schedule your CronJob to run every 10 mins starting at 10h of the day. Or:

0 0/10 * ? * 6/1 *

will schedule your CronJob to run every 10 mins starting on Friday.

The important thing to keep in mind while using this particular approach is to be aware of the timezone that your cluster is running in:

All CronJob schedule: times are based on the timezone of the kube-controller-manager.

If your control plane runs the kube-controller-manager in Pods or bare containers, the timezone set for the kube-controller-manager container determines the timezone that the cron job controller uses.

More info/examples about scheduling can be found below: