Using set_time_limit() or max_execution_time, does not "really" limits (except on Windows) the execution time, because as stated in PHP manual:
Note:
The set_time_limit() function and the configuration directive max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), stream operations, database queries, etc. is not included when determining the maximum time that the script has been running. This is not true on Windows where the measured time is real.
A solution is proposed in PHP comments to have a "real" execution time limit like what I'm looking for, but I found it unclear/confusing.
Maximum execution time (max_execution_time) is a time limit on how long a PHP script can run. It is a way hosting providers can limit the use and abuse of server resources, especially for shared hosting. The actual default value depends on the hosting, but it-s usually set to 30 (i.e. 30 seconds).
One important aspect of PHP programs is that the maximum time taken to execute a script is 30 seconds. The time limit varies depending on the hosting companies but the maximum execution time is between 30 to 60 seconds.
I might be wrong, but as far as I understand you ask for explanation of the "PHP comments" solution code.
The trick is to spawn a child process, using pcntl_fork function, which will terminate the original (parent) process after some timeout. Function pcntl_fork returns process id of newly created child process inside a parent process execution thread and zero inside child process execution thread. That means parent process will execute the code under if statement and the child process will execute code under else. And as we can see from the code, the parent process will perform endless loop while child process will wait 5 seconds and then kill his parent. So basically you want to do something like this:
$real_execution_time_limit = 60; // one minute
if (pcntl_fork())
{
// some long time code which should be
// terminated after $real_execution_time_limit seconds passed if it's not
// finished by that time
}
else
{
sleep($real_execution_time_limit);
posix_kill(posix_getppid(), SIGKILL);
}
I hope I've exlained it well. Let me know if you sill have question regarding this solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With