PHP sleep versus Cron-job

454

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?

896

Answer

Solution:

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
221

Answer

Solution:

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.

844

Answer

Solution:

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.

People are also looking for solutions to the problem: php - How can I prevent the comments section in my WordPress site from spanning the full screen?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.