Reputation: 6895
I have a php script I need to run every 5 seconds (run, wait until it's done, wait 5 seconds, run again)
I have two ways of doing it. either have an infinte loop in the script with a sleep function that would look like that:
while (1)
{
do_stuff();
sleep 5;
}
or have bash script that will run the script and wait for 5 seconds. It would look like that
while [ 1 ]; do
php script.php &
wait
sleep 5
done
I was wondering what is the most efficient way to do it.
The php script i am running is a codeigniter controller that does a lot of database calls..
Upvotes: 2
Views: 1643
Reputation: 3730
This might depend on what else the system is doing. I would think that the BASH solution could be better handled by the system to free up resources for other applications.
The number of database calls seems like it would be less important, because you need to make those either way. The cost of running the script from BASH is the time to build up and strip down the CodeIgniter framework. But CodeIgniter is already designed to do this in a normal web application and performs fast enough.
Upvotes: 1
Reputation: 3799
Typically all PHP scripts have a timeout - unless you are running from CLI - so your first method will work for 30 to 60 seconds (depending on your server configuration) and then will be forcibly terminated.
I'd tend to suggest either a command-line option or even (and this depends on how regularly you want the code to run) a cron command to execute it.
Upvotes: 1
Reputation: 360562
If you're doing a lot of DB calls, then do the sleep within php. That way you're not paying the php startup penalty, the connect-to-the-db penalty, etc... that'l be incurred if you're sleeping in bash.
When you do the bash loop, you'll be starting/running/exiting your script each iteration, and that overhead adds up quickly on long-running scripts.
On the other hand, at least you'll start with a "clean" environment each time, and won't have to worry about memory leaks within your script. You may want to combine both, so that you loop/sleep within PHP (say) 100 times, then exit and loop around in Bash.
Upvotes: 8