php set_time_limit()用法测试详解

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

 代码以下
1 set_time_limit(5);
2 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 这里找到根源所在,实际上是上面的写法有问题,例如使用下述代码:html

 代码以下
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中写到:linux

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.web

sql

 

 代码以下
1 //set_time_limit(0);
$i=1500;
include ("inc/conn.php");
while($i>0)
{
$sql="INSERT INTO php (php)
VALUES ('$i')";
if ($conn->execute($sql)===flase)
{
//echo "数据插入错误".$conn->errormsg();
}
else
{
$phpid=$conn->Insert_ID();
echo $i."已经存入数据库,编号:".$phpid;
}
$i--;
echo "
";
}
?>

注意:sleep函数暂停的时间也是不计入脚本的执行时间的。因此也是第一个测试失败的缘由。数据库

当你的页面有大量数据时,建议使用set_time_limit()来控制运行时间,默认是30s,因此须要你将执行时间加长点,如 set_time_limit(300)  ,其中将秒数设为0 ,表示持续运行!apache

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

注意:这个函数的运行须要你关闭安全模式,在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页面的最大执行时间,好比下面:

 代码以下
1 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秒就有提示信息了.

相关文章
相关标签/搜索