tags:

views:

190

answers:

3

I'm writing a script that needs to be called at a random time during the day, but am not sure how to accomplish this.

I don't want to waste server resources to run a cron job every minute.

I want the script to be called at random, so generating the random times for say a month in advance and then creating cron jobs for each of them isn't what I'm looking for.

Also this script only needs to be executed once a day.

Thanks in advance!

+2  A: 

Have each run submit a further run using 'at' with a random time? That wouldn't guarantee it ran every day, but you could get that as an average.

Colin Fine
I was going to say that it can't be done, but I hadn't even considered modifying the crontab itself! Nice!
Matchu
That won't work because the intial cron job would still have to run often.
Jan Kuboschek
...or have a cron job which runs everday to generate the 'at' job at a random time. Although the reason for running at a random time remains a mystery.
symcbean
@Jan Kuboschek: Maybe I'm misinterpreting the initial answer. I thought the point was that the cron job, after each run, would modify the crontab to set itself to run again at a random time.
Matchu
@Matchu In that case you're spot-on.
Jan Kuboschek
+1 for inventiveness!
Sohnee
you could look at wp-cron.php used by WordPress, which does a GREAT job of making a "fake" cron.
Brad
A: 

If you have access to it, modify the crontab file whenever your target script runs and add in a random time.

Jan Kuboschek
A: 

This will add a cron job:

cat "* * * * * /path/to/script" | crontab

You need to generate a proper time instead of * * * * * (it will run every minute otherwise).

cat "* * * * * /path/to/script" | crontab -r

will remove the job. So, now you need to call those from PHP script, I don't remember exactly how it's done in PHP.

EDIT

http://php.net/manual/en/function.system.php

MORE EDIT

Every time script executes, it's two last operations might be removing the current cron job and generating another one for the next day.

EVEN MORE EDIT

http://codepad.org/Z1B2v4lF -- here's how I would do it in Python. This may run more than once a day. If running only once a day is a must, you can add a day-of-month value as well.

hudolejev