views:

529

answers:

6

Hey!

I have this mail script I have to run a few times. To start the script I will use cron, but the script has to run 2 or 3 more times (with an hour apart).

What's the best way to do this? To use the sleep command for an hour, or at the end of the script, place some code, so that the script will create a new cron job to run it self after an hour?

Thanks

A: 

I'm not sure either approach (sleeping for an hour, or creating cron jobs from php) is ideal, how about a cron job that runs every hour anyway, then your php script checks whether it should run?

Colin Pickard
A: 

Check out the unix utility 'at': http://unixhelp.ed.ac.uk/CGI/man-cgi?at

psanf
A: 

Try the at command -> man at

sleeping is not a good idea (too many died in the bed before :-) )

Blauohr
+3  A: 

Unless there's some cost savings in keeping the script running in memory, you're better off using cron to invoke it every hour, as needed.

0 0-2 * * * /usr/local/bin/mail-script.php

You can choose multiple hours using the - syntax, or the comma syntax:

0 0,1,2,3 * * * /usr/local/bin/mail-script.php

If it needs to maintain some form of state, use a temporary file to keep saved state.

Do:

> man 5 crontab

To see if your *nix handles the above cases.

Finally, unless you know the script has to run only 2-3 times, you're better off putting the logic about whether to "run or not to run" in the PHP script itself, and then just run it every hour.

razzed
A: 

Why not just set the cron criteria so it fires those specific times? Cron is pretty flexible in that aspect.

Update your question with when you want it to fire off and I can give an example.

Josh W.
+1  A: 

One advantage of using sleep() is that it could be more portable. For example, on many systems I work with, users are not allowed to have their own cron jobs - so writing your program to take care of its own timer-ness might be an advantage.

An alternative to sleep() might be using SIGALRM (so your script catches an interrupt and executes code at a certain interval - when that interrupt is thrown.)

I mean, I'd recommend using cron - but here are some alternatives!

rascher