Why doesnt set_time_limit work as expected? [duplicate]

笑着哭i 提交于 2019-12-10 23:38:00

问题


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.


回答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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/7493023/why-doesnt-set-time-limit-work-as-expected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!