2

Take a quick look at the following snippet:

<?
set_time_limit(5);
sleep(30);
echo 'done';
?>

When I execute this on my boxes, the script takes the full 30 seconds, and displays 'done'.

Why?

Shouldnt it terminate in 5 seconds and not give the script the time to display 'done'?

This is NOT in CLI mode. Nginx + PHP_FPM.

Any ideas?


I have opted to put the 'answer' in here as there is quite a few GOOD and VALID answers below. But... It appears to be a specific issue with sleep.

<?
set_time_limit(5);
while(true==true){
}
sleep(30);
echo 'done';
?>

Works as expected.

anonymous-one
  • 14,454
  • 18
  • 60
  • 84

3 Answers3

1

To quote the manual:

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.

The sleep call doesn't adds to the execution time because it's an OS process and nothing is being done.

hakre
  • 193,403
  • 52
  • 435
  • 836
Alix Axel
  • 151,645
  • 95
  • 393
  • 500
1

According to the set_time_limit() docs:

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.

The call to sleep() doesn't count as execution time (except under Windows). This behavior is well documented in the comments on the set_time_limit() page.

Community
  • 1
  • 1
Asaph
  • 159,146
  • 25
  • 197
  • 199
0

From php.net: When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.

You could subtract to match the time you want

hakre
  • 193,403
  • 52
  • 435
  • 836
EO2
  • 364
  • 1
  • 7