ultimatebob

Lifer
Jul 1, 2001
25,135
2,445
126
I'm trying to schedule a Linux cron job that runs a software update on about 20 systems around 2 AM. I don't want them run all at the same time, though, because they'll kill the update server if they all run at once.

Does anybody know of a way to add a randomizer to the time when a cron job kicks off?
 

Red Squirrel

No Lifer
May 24, 2003
67,397
12,142
126
www.anyf.ca
I don't think that's doable through cron, for my backup jobs what I do is just stagger them. I have this weird issue that I was never able to figure out, but if there's too much disk I/O the system starts to crash and random jobs get killed. So to remedy that I have the backup jobs staggered by about 1 hour. They all run off the same server so it's easier to do because it's all in one place.

For the updates what you could do is have a randomizer in the script itself. I'm not sure off the top of my head how to generate a random number within a bash script but it's fairly easy to do with C++ if you want to write a basic program that you call in the script.

Actually another thing you could do is have the script create a temporary file somewhere then delete it after. When the script runs it first checks if that file exists, if it does, it waits like 20 seconds then deletes the file and executes. It would sorta add some pseudo randomness and staggering to it.
 

ultimatebob

Lifer
Jul 1, 2001
25,135
2,445
126
I found this solution, where you add the following random sleep interval before the job runs in the crontab entry:

0 2 * * * sleep $[ ( $RANDOM % 900 ) + 1 ]s ;chef-client

This causes the clients (in this case, chef) to run somewhere in between 2 AM and 2:15 AM.