user562854
user562854

Reputation:

Script has to be executed X times in 24h. How do I randomize that?

I have a PHP script, which does something in a matter of seconds (not running for a long time). I need this script to be executed, let's assume, 12 (this can change) times a day. 24 / 12 = 2 hours.

I could just execute the script each 2 hours, but I need it to be randomized along the 24 hours.

That means that script doesn't have to be executed at 01:05 PM, 03:05 PM, 05:05 PM, but rather at 01:37 PM, 03:11 PM, 05:46 PM. I guess you've understand the point. Sorry for not being very clear.

(cron & other tools (if required) can be installed. running debian 6)

Bounty (100 rep) will be offered for a working solution.

Upvotes: 2

Views: 616

Answers (4)

chepner
chepner

Reputation: 531075

Let's say you want your script to run N times a day. Then create a bash script my_php_runner.bash like the following:

#!/bin/bash

N=12  # 50 times a day

let WAIT_TIME=86400/$N

while [[ $n -gt 0 ]]; do
    php yourscript.php

    # Sleep for $WAIT +/- 300 seconds
    sleep $(( $WAIT - 300 + $RANDOM%600 ))
    ((n--))
done

It will run your script 12 times, waiting between 115 and 125 minutes between runs. Then add something like

0 0 * * * my_php_runner.bash

in cron to run the bash script once a day.

Upvotes: 1

William Entriken
William Entriken

Reputation: 39253

If you strictly must run X times per day:

  • Manually (or make a simple script) to divide the day in to X portions.
  • Make a cron line for each portion.
  • Delay your script a random amount between 0 and 24H/x during run.

If not:

  • Cron run at midnight.
  • PHP delays using poisson distribution then processes.
  • End of script runs a new script unless its processing crossed midnight.

Upvotes: 0

lanzz
lanzz

Reputation: 43168

You can always sleep(rand(60, 1.5 * 60)) at the start of the cronjob to offset its execution. You will have an idle PHP process during this time, which might or might not be a problem.

Upvotes: 0

hackartist
hackartist

Reputation: 5264

Here is how I would do it: Setup a cron to tell it to run every 2 hours like this

0 /2 * * * php youscript.php

This says run yourscript.php every other hour on the hour. Then in the top of the php code itself just put:

sleep(rand(5*60,50*60));

this will make the script pause a random amount of time between 5 and 50 minutes before doing its work. You can change the min and max of the random number to ensure that there is a minimum time between runs.

If you wanted it to run 24 times instead do

0 * * * * php youscript.php

or even 48 times a day

0,30 * * * * php youscript.php

Upvotes: 2

Related Questions