当前位置:首页 > PHP教程 > php函数 > 列表

php set_time_limit()用法测试详解

发布:smiling 来源: PHP粉丝网  添加日期:2014-02-23 12:15:48 浏览: 评论:0 

在php中set_time_limit函数是用来限制页面执行时间的,如我想把一个php页面的执行时间定义为5秒就可以set_time_limit(5)了。

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

实例代码如下:

  1. set_time_limit(5); 
  2. for ($i = 0; $i < 100; $i++) { 
  3.     echo date('Y-m-d H:i:s') . "n"
  4.     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 这里找到根源所在,其实是上面的写法有问题,例如使用下述代码:

  1. set_time_limit(5); 
  2. 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.

实例代码如下:

  1. <?php  
  2. //set_time_limit(0);  
  3. $i=1500;  
  4. include ("inc/conn.php");  
  5. while($i>0)  
  6. {  
  7. $sql="INSERT INTO php (php)  
  8. VALUES ('$i')";  
  9. if ($conn->execute($sql)===flase)  
  10. {  
  11. //echo "数据插入错误".$conn->errormsg();  
  12. }  
  13. else  
  14. {  
  15. $phpid=$conn->Insert_ID();  
  16. echo $i."已经存入数据库,编号:".$phpid;  
  17. }  
  18. $i--;  
  19. echo "<hr>";  
  20. }  
  21. ?> 

注意:sleep函数暂停的时间也是不计入脚本的执行时间的,所以也是第一个测试失败的原因,当你的页面有大量数据时,建议使用set_time_limit()来控制运行时间,默认是30s,所以需要你将执行时间加长点,如 set_time_limit(300),其中将秒数设为0,表示持续运行!

如:set_time_limit(0)表示长时间链接运行!

注意:这个函数的运行需要你关闭安全模式,在php.ini中将safe_mode = Off 安全模式设置为Off,否则将会出现下面错误:

Warning: set_time_limit() [function.set-time-limit]: Cannot set time limit in safe mode in

再次注意的是:在php.ini可以通过定义max_execution_time来设置PHP页面的最大执行时间.比如下面:

set_time_limit(900);

这个函数指定了当前所在php脚本的最大执行时间,虽然设定值是900秒,实际上最大执行时间=php.ini里的max_execution_time数值 - 当前脚本已经执行的时间 + 设定值

假如php.ini里的max_execution_time=30,当前脚本已经执行10秒,则:最大执行时间=30-10+900=920秒。

php中设置set_time_limit不起作用的解决方法:

set_time_limit用来设置脚本的超时时间,用法如下:

set_time_limit(秒数); 

规定从该句运行时起程序必须在指定秒数内运行结束, 超时则程序出错退出.但是有时候设置set_time_limit没有效果,set_time_limit函数最好是在linux下执行,windows执行可能也无效.

解决方法:修改php.ini里的max_execution_time = 30了,这个默认是30秒,修改为max_execution_time = 300,重新启动apache服务器,这样超时设置为300秒就有提示信息了.

Tags: set_time_limit 用法测试

分享到:

相关文章