Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it so bad to run a PHP script continuously?

I have a map. On this map I want to show live data collected from several tables, some of which have astounding amounts of rows. Needless to say, fetching this information takes a long time. Also, pinging is involved. Depending on servers being offline or far away, the collection of this data could vary from 1 to 10 minutes.

I want the map to be snappy and responsive, so I've decided to add a new table to my database containing only the data the map needs. That means I need a background process to update the information in my new table continuously. Cron jobs are of course a possibility, but I want the refreshing of data to happen as soon as the previous interval has completed. And what if the number of offline IP addresses suddenly spike and the loop takes longer to run than the interval of the Cron job?

My own solution is to create an infinite loop in PHP that runs by the command line. This loop would refresh the data for the map into MySQL as well as record other useful data such as loop time and failed attempts at pings etc, then restart after a short pause (a few seconds).

However - I'm being repeatedly told by people that a PHP script running for ever is BAD. After a while it will hog gigabytes of RAM (and other terrible things)

Partly I'm writing this question to confirm if this is in fact the case, but some tips and tricks on how I would go about writing a clean loop that doesn't leak memory (If that is possible) wouldn't go amiss. Opinions on the matter would also be appreciated.

The reply I feel sheds the most light on the issue I will mark as correct.

like image 629
Hubro Avatar asked Mar 20 '11 22:03

Hubro


People also ask

Can a PHP script run forever?

You can make it run forever by either setting the value or call set_time_limit in your script (http://php.net/manual/en/function.set-time-limit.php).

How do I run a PHP script continuously?

The best way to achieve OP's goal is to use one cron job to poll a script every 1, 5, or however many minutes. That script should check a file (or db value) for a date + time. If the date + time is ≤ the current time, it should look through the full queue of tasks and do any that are ready.


1 Answers

The loop should be in one script which will activate/call the actual script as a different process...much like cron is doing.
That way, even if memory leaks, and non collected memory is accumulating, it will/should be free after each cycle.

like image 120
Itay Moav -Malimovka Avatar answered Oct 31 '22 05:10

Itay Moav -Malimovka