bashcronsh

Cron jobs and random times, within given hours


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 jobs in linux.


Solution

  • If I understand what you're looking for, you'll need to do something a bit messy, like having a cron job that runs a bash script that randomizes the run times... Something like this:

    crontab:

    0 9 * * * /path/to/bashscript
    

    and in /path/to/bashscript:

    #!/bin/bash
    
    maxdelay=$((14*60))  # 14 hours from 9am to 11pm, converted to minutes
    for ((i=1; i<=20; i++)); do
        delay=$(($RANDOM%maxdelay)) # pick an independent random delay for each of the 20 runs
        (sleep $((delay*60)); /path/to/phpscript.php) & # background a subshell to wait, then run the php script
    done
    

    A few notes: this approach it a little wasteful of resources, as it fires off 20 background processes at 9am, each of which waits around for a random number of minutes (up to 14 hours, i.e. 11pm), then launches the php script and exits. Also, since it uses a random number of minutes (not seconds), the start times aren't quite as random as they could be. But $RANDOM only goes up to 32,767, and there are 50,400 seconds between 9am and 11pm, it'd be a little more complicated to randomize the seconds as well. Finally, since the start times are random and independent of each other, it's possible (but not very likely) that two or more instances of the script will be started simultaneously.