Reputation: 891
I want a cronjob to run every one hour randomly. (i.e if the first job runs at 58 minutes,the second job should run at 47 minutes and the third one at 52 minutes and so on) But this should run randomly for everyone hour. Is there a way to do this?
Upvotes: 5
Views: 8349
Reputation: 207445
You could run a job every hour, on the hour, that sleeps up to 3,599 seconds and then executes your script:
0 * * * * /bin/bash -c 'sleep $((RANDOM%3600))' && /path/to/yourScript
Or, with Perl:
0 * * * * /path/to/perl -e 'sleep int rand 3600' && /path/to/yourScript
Or, using PHP
if you prefer that to Perl
:
0 * * * * /path/to/php -r 'sleep(rand(0,3599));' && /path/to/yourScript
You can find the path to Perl
with:
which perl
likewise for PHP
:
which php
Upvotes: 8
Reputation: 123
Instead of using perl or even php, just use the BASH $RANDOM built in divided by 3600 which equals one hour like so.
0 * * * * sleep $((RANDOM%3600)) && /path/to/yourScript
Keep in mind that you will probably have some race conditions with a script sleeps randomly close to an hour depending on how long it takes for your script to execute.
Upvotes: 6