登录  /  注册
首页 > php教程 > php手册 > 正文
php set_time_limit()用法测试详解
php中文网
发布: 2016-06-13 10:16:54
原创
1231人浏览过

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

一个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.

代码如下 复制代码
//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 ,表示持续运行!

如: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秒就有提示信息了.

来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 技术文章
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2023 //m.sbmmt.com/ All Rights Reserved | 苏州跃动光标网络科技有限公司 | 苏ICP备2020058653号-1

 | 本站CDN由 数掘科技 提供

登录PHP中文网,和优秀的人一起学习!
全站2000+教程免费学