Anyone who has dealt with importing or exporting data has likely encountered the problem of a script running into a short execution time limit. The quickest solution often involves adjusting the PHP configuration or completely disabling the limit at the beginning of the script. However, extending the execution time significantly or disabling it altogether introduces security risks. An unstoppable background script can lead to excessive resource consumption.
When processing tasks over iterations, it's possible to monitor individual passes in time and attempt to gracefully terminate execution before the time limit expires.
// initialize basic variables for further work $maxExecutionTime = (int)ini_get('max_execution_time'); $estimateCycleTime = 0; $startTime = microtime(true); // For demonstration purposes, we use an "infinite" loop with a simulated task lasting 10 seconds while (true) { sleep(10); // Calculate the current runtime $currentRunTime = microtime(true) - $startTime; // Termination can be done either with a fixed constant // or by measuring the time of one pass and trying to use // the longest possible segment of the runtime // limit (has its problem). if ($estimateCycleTime === 0) { $estimateCycleTime = $currentRunTime; } // Check if the iteration stop time is approaching. // Subtract the time of one pass, which likely won't fit // within the window. if (($maxExecutionTime - $estimateCycleTime) < $currentRunTime) { echo 'Time is end'; break; } }
Early termination based on the calculation of one pass is suitable for cases where there are a large number of passes that need to be processed in as few new executions as possible, and each operation in one pass is similarly time-consuming. If individual passes differ in their time requirements, a coefficient must be added to the pass time. Another option is to use a predefined time:
$beforeEndTime = 1; if (($maxExecutionTime - $beforeEndTime) < $currentRunTime) { echo 'Time is end'; break; }
If the script continues after iteration, such as closing connections to API endpoints, closing files, or performing other operations, it's essential to remember to add this time.
The above is the detailed content of Basic Protection Against Max Execution Time Limit. For more information, please follow other related articles on the PHP Chinese website!