PHP 超时控制

1. PHP 的超时函数:set_time_limit ,但这个函数对 sleep, exec,数据库等操作,是不计算时间的,换句话说,这是不精确的超时控制,比如下面两个例子:

    a:

<?php
set_time_limit(5);
while (true) {
  //其他操作
}
echo "执行完毕";
?>

    b:

    

<?php
set_time_limit(5);
$db   = mysqli_connect('localhost','root','root','table');
$sql = "SELECT SLEEP(10) FROM table;";
$db->query($sql);
echo "执行完毕";
?>

 

2. 要精确控制的话,如果在CLI下执行,可以这样:

   

<?php
$real_execution_time_limit = 60; //时间限制

if (pcntl_fork())
{
    // some long time code which should be
    // terminated after $real_execution_time_limit seconds passed if it's not
    // finished by that time
}
else
{
    sleep($real_execution_time_limit);
    posix_kill(posix_getppid(), SIGKILL); 
}

 

如果是web中,以fpm 方式执行,那么可以修改:/etc/php5/fpm/pool.d/www.conf 中的 request_terminate_timeout。 如果想看哪些脚本超时了,可以配置:request_slowlog_timeout 和 slowlog

另外需要配置apache 的站点中配置 FastCgiExternalServer -idle-timeout 300

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值