I need the ability to run a PHP script 20 times a day at completely random times. I also want it to run only between 9am - 11pm.
I\'m familiar with creating cron job
at -f [file] [timespec]
or
echo [command] | at [timespec]
or
at [timespec]
... and interactive specification
like script
's recording.
At runs the text provide on stdin or in the file specified by -f [file]
.
Here's the [timespec] grammar. It can be something like:
0100
, 2359
, 1620
now + 10 minutes
2071-05-31 - 5 hours 12 minutes UTC
If you're explicitly specifying the timezone, some versions of the timespec might only allow UTC
for the optional timezone argument.
cat script.sh | at now + $(($RANDOM % 10)) hours $(($RANDOM % 60)) minutes
at -f script.sh now + $(($RANDOM % 10)) hours $(($RANDOM % 60)) minutes
You can test the bash parsing by pre-pending echo
and escaping the |
(pipe).
echo cat script.sh \| at now + $(($RANDOM % 10)) hours $(($RANDOM % 60)) minutes
echo at -f script.sh now + $(($RANDOM % 10)) hours $(($RANDOM % 60)) minutes
To see jobs scheduled, use atq
and job contents (environment vars, setup, and command/script) with at -c [jobid]
.
The system is part of cron, and the interactive prompt actually captures the whole current state of your shell, so you can run commands without specifying absolute paths.
My first thought would be to create one cron job launching 20 randomly scheduled at jobs. The at
utility (http://unixhelp.ed.ac.uk/CGI/man-cgi?at) is used for executing commands at specified time.
I ended up using sleep $(( 1$(date +%N) % 60 )) ; dostuffs
(compatible with bash & sh)
The 1 prefix is to force NON base 8 interpretation of date +%N (e.g. 00551454)
Do not forget to escape % using \% in a crontab file
* * * * * nobody sleep $(( 1$(date +\%N) \% 60 )) ; dostuffs
al-x 's Solution does not work for me since crontab commands are not executed in bash but in sh I guess. What does work is:
30 8 * * * bash -c "sleep $[RANDOM\%90]m" ; /path/to/script.py
I realize it's an older thread, but I want to add one random-value related thing that I use a lot. Instead of using the $RANDOM variable with a fixed and limited range, I often make arbitrary-range random values in the shell with
dd if=/dev/urandom bs=4 count=1 2>/dev/null | od -N4 -t u4 -A none
so you can do, for example,
FULLRANDOM=$(dd if=/dev/urandom bs=4 count=1 2>/dev/null | od -N4 -t u4 -A none)
and overcome some the restrictions that were discussed in this thread.
So I'm using the following to run a command between 1AM and 330AM
0 1 * * * perl -le 'sleep rand 9000' && *command goes here*
That has been taking care of my random needs for me. That's 9000 seconds == 150 minutes == 2.5 hours