最近我正在运行一个运行为php-fpm / nginx的运行状况检查脚本,并且我希望在比同一服务器上的常规php脚本执行时间更短的时间后使此脚本触发错误。如果健康检查需要花费大量时间来执行,那么必定是错误的。
但我没想出为什么该脚本会忽略执行时间限制。例如:
//healthcheck.php
error_reporting(E_ALL);
error_reporting(1);
echo "initial max_execution_time: " . ini_get('max_execution_time') . "\n";
print_r(set_time_limit(2));
echo " - set_time_limit\n";
print_r(ini_set('max_execution_time', 2));
echo " - max_execution_time\n";
echo "altered max_execution_time: " . ini_get('max_execution_time') . "\n";
sleep(4);
print_r(getrusage());
echo 'Current PHP version: ' . phpversion() . "\n";
die('it should not happen');
返回:
initial max_execution_time: 30
1 - set_time_limit
2 - max_execution_time
altered max_execution_time: 2
Array
(
[ru_oublock] => 0
[ru_inblock] => 0
[ru_msgsnd] => 0
[ru_msgrcv] => 0
[ru_maxrss] => 15032
[ru_ixrss] => 0
[ru_idrss] => 0
[ru_minflt] => 1681
[ru_majflt] => 0
[ru_nsignals] => 0
[ru_nvcsw] => 26
[ru_nivcsw] => 9
[ru_nswap] => 0
[ru_utime.tv_usec] => 5999
[ru_utime.tv_sec] => 0
[ru_stime.tv_usec] => 6998
[ru_stime.tv_sec] => 0
)
Current PHP version: 5.4.35
it should not happen
答案 0 :(得分:2)
这是另一种选择:
2)使用declare(),参见http://php.net/manual/en/control-structures.declare.php
例如:
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var arr= JSON.parse(xhr.responseText);
//var str = JSON.stringify(xhr.responseText, null, 2);
//alert(str);
var obj = $.parseJSON(xhr.responseText);
for (var key in obj.results) {
var values = obj.results[key];
for (var v in values) { //v - files, details
if(v=="files")
{
var files = values.files;
for (i = 0; i < files.length; i++) {
document.write(" "+ files[i]);
}
}
document.write( " "+values.details+" "+values.type+" "values.user +"<br>");
}
}
}
来自:http://bytes.com/topic/php/answers/620062-how-handle-php-execution-timeouts-gracefully
我不推荐使用$ GLOBALS,我将时间轴作为register_tick_function()的arg传递。 http://php.net/manual/en/function.register-tick-function.php
答案 1 :(得分:1)
最大执行时间不受系统调用流的影响 运营等。
我猜测sleep
使用系统调用。
通过一些虚拟的长时间运行计算替换sleep
调用会使脚本按预期失败:
<?php
//healthcheck.php
error_reporting(E_ALL);
error_reporting(1);
echo "initial max_execution_time: " . ini_get('max_execution_time') . "\n";
print_r(set_time_limit(2));
echo " - set_time_limit\n";
print_r(ini_set('max_execution_time', 2));
echo " - max_execution_time\n";
echo "altered max_execution_time: " . ini_get('max_execution_time') . "\n";
$dummy = 2;
for($i=0;$i<1000000000;$i++){
$dummy *= 2;
}
print_r(getrusage());
echo 'Current PHP version: ' . phpversion() . "\n";
die('it should not happen');
输出:
PHP致命错误:超过2秒的最长执行时间 第14行/home/hjusforgues/maxExecutionTime.php
答案 2 :(得分:0)
PHP的最长执行时间会忽略睡眠持续时间。
<?php
set_time_limit(20);
while ($i<=10)
{
echo "i=$i ";
sleep(100);
$i++;
}
?>
Output:
i=0 i=1 i=2 i=3 i=4 i=5 i=6 i=7 i=8 i=9 i=10