Loop for a Period of Time

This trick is useful if you are going to be looping through a lot of data and it will take longer than five minutes. 

If a script runs too long in a browser several (bad) things could happen. Either the browser will time out, or the gateway will time out or the server will terminate your PHP script abruptly and without warning :(

The workaround is to loop for a set period of time which is less than five minutes. 

This will cause the script to restart, which resets the five minute time limit in the browser, gateway and the PHP execution time limit on the server.

// sets the script execution time to unlimited. However as mentioned above the practical execution time is still limited by the gateway timeout, and browser timeout.
set_time_limit(0);
// When $endtime > microtime(true) the loop will terminate.

set_time_limit(0);
$time_start = microtime(true);
$endtime = $time_start + 250; // loop for 250 seconds
do {} while ($endtime > microtime(true));

Example:

PHP
set_time_limit(0); // set this a little higher than your loop time.
$time_start = microtime(true);
$endtime = $time_start + 250;

do {
    // calculate something for 250 seconds
} while ($endtime > microtime(true));

Produces the result: 

The "do loop" runs for 250 seconds.
After the loop has run for the specified period of time, save variables in a file and restart the script.  When the script restarts, just load the variables and pick up where the looping left off.

It might also be useful to put another ending condition in the loop.
For example while ($endtime > microtime(true) && $notyetdone);
This will allow you to terminate the loop by setting $notyetdone = false before the five minute time has completed. This should be done if the intended task has been completed before the 5 minute limit.

 

Copyright © Lage.us Website Development | Disclaimer | Privacy Policy | Terms of Use