~ 1 min read

Scheduling randomized cron - within an hour or within a minute

It is usually a good idea in general to add slight randomness to the start time of a cron job, especially if you are accessing some 3-d party resource to prevent flooding of 3-d party at the top of the hour or at the top of the minute.

This will run the cron job every day sometime between 2pm-3pm and 2am–3am in a randomized manner

0 2,14 * * * sleep $(expr $RANDOM \% 3600); ~/bin/batch_job

If you want just a bit of randomness then you can do something like this

0 2,14 * * * sleep $(expr $RANDOM \% 60); ~/bin/batch_job

Which will start the cron within the first minute of 2pm and 2am in a randomized manner

One note to make here is that $RANDOM is a 16 bit number and has limited range so

  1. Using small modulo (especially 10) won’t produce uniform results
  2. If you need to generate a large random number you may need something else like shuf for example