Don P
Don P

Reputation: 63547

PHP sleep versus Cron-job

I want a script to run randomly between 30seconds to 1minute during the day between between 8am to 8pm.

Is there anything stopping me from just opening a PHP script one time with a 30-60sec sleep in a loop? And then it checks whether the time is between the 8am and 8pm?

What is the disadvantage to doing this compared to a Cron job? Can a Cron job run at random times?

Upvotes: 2

Views: 1676

Answers (3)

mrok
mrok

Reputation: 2710

Definitely max_execution_time can stop you (if your hosting does not let you set it to infinity). Sleep time is not taken into account, but still after some time you can reach a limit.

Upvotes: 4

KingCrunch
KingCrunch

Reputation: 131811

The Disadvantage is, that they run forever. If it fails, you probably wont realize it instantly, and if you built it wrong, it will consume much memory and cpu without freeing it. When using cronjobs you can be sure, that it will start a clean and fresh process every time it's needed.

Additional: It's sooo damn easy to setup a cronjob, so why not?

0,30 8-18 * * * php myscript.php

Upvotes: 4

arkascha
arkascha

Reputation: 42885

You can implement such a long lasting scheme in php. It works (provided you use php from the command line...). The only thing that might be a minor disadvantage is that there is no recovery in case of a failure. This would be different when using a cron job: a new process would simply be started. However this obviously introduces other risks, so there is no 'better' way.

Cron cannot start processes at random times. however you can start your process at fixed intervals and use an initial sleep command of random length. That should have the same effect.

Upvotes: 2

Related Questions