首页 > PHP > php set_time_limit

php set_time_limit

2013年8月14日 发表评论 阅读评论

一个php脚本通过crontab每5分钟执行一次,考虑到脚本执行时间会超过5分钟,特意用set_time_limit(290)来控制脚本在290秒退出。某天突然发现后台有多个该脚本的进程在执行,也就是说set_time_limit(290)没有起作用。为了证明,特意使用如下代码测试。

set_time_limit(5);

for ($i = 0; $i < 100; $i++) {
    echo date('Y-m-d H:i:s') . "\n";
    sleep(1);
}

无论是在web还是CLI下,上述脚本并没有在5秒钟后退出。后来加上ini_set(‘max_execution_time’, 5)测试,结果一样。那是不是说明set_time_limit函数根本就没有用呢?其实不然,在 http://stackoverflow.com/questions/5874950/set-max-execution-time-in-php-cli 这里找到根源所在,其实是上面的写法有问题,例如使用下述代码:

set_time_limit(5);

for (;;) {
}

执行后,大概5秒钟就可以看到”Fatal error: Maximum execution time of 5 seconds exceeded in”类似这样的错误提示。说明set_time_limit是起作用的。现在在去看看官方文档(http://www.php.net/manual/en/function.set-time-limit.php)上关于此函数的说明,在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.

注意:sleep函数暂停的时间也是不计入脚本的执行时间的。所以也是第一个测试失败的原因。



欢迎转载,转载请注明文章出处,谢谢!
垃圾有点差凑合看还不错很精彩 (还没有人进行评分)
Loading...Loading...
分类: PHP 标签:
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.

无觅相关文章插件,快速提升流量