Can I make cron "random"?

at has a simpler interface for this type of purpose if at is installed, the machine is running atd and the user is allowed to use the command.

For example (check the exact syntax using man at or info at),

at -f file now + 53 minutes

or

at -f file now + 2 hours

will run the commands in the specified file in 53 minutes or 2 hours, respectively.

at can then be re-run at the start of the scheduled job with suitable (random or otherwise) start, count, and time-units.

Edit

As Arjan points out helpfully below, if you are using this for other than a toy application you need to think about issues such as what happens

  1. if the next run starts before the previous one finishes (e.g. is the script re-entrant?) or

  2. if a run fails to complete correctly or

  3. if the next run fails to start at all or on time (e.g. what happens if the machine is off when the next run is due to start) and

  4. about the logging and reporting of failed or successful runs.


I have many commands in /etc/crontab doing all kinds of things and some need precision in seconds. Now cron can have finer resolution while keeping all the times visible and centralised.

This example gets and parses a web page between 10 and 50 seconds before every 5 minutes:

4-59/5 * * * * root (sleep $(($RANDOM\%40+10))) && /etc/munin/plugins/someplugin prefetch

It doesn't have to have an exact time as the data is slow moving, but it helps to keep munin-node execution time as low as possible by not having to wait for webpages. (The plugin further caches the page for 30 mins to reduce unnecessary hits, but needs to update a database every 5 mins).

Note the \% — cron substitutes % for "\n" — useful for keeping mail text on one line.


Internally to cron, I don't think such a feature exists. I think the best solution would be to place your command into a shell script, and place a random sleep interval at the top of the script and use the $RANDOM variable. Then run the script once a day in a regular cron job.

#!/bin/bash
sleep $(($RANDOM%5))
/path/to/command -param1 -param2

Tags:

Cron