色婆ijqwj 发表于 2017-3-20 10:29:32

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
页: [1]
查看完整版本: PHP 超时控制