我需要创建一个循环,当它超过20秒时结束.我尝试了以下代码,但它无法运行,永远运行.
编辑:对于简单的代码,它将停止正常,但使用include_once并包括外部文件即使在20秒到期后仍保持运行
bot.php
$starttime = time();
while (time() - $starttime < 20) {
include_once 'onefile.php';
include 'somefile.php';
include 'somefile2.php';
}
Run Code Online (Sandbox Code Playgroud)
编辑2:
有了Josh Trii Johnston的回答,如果没有在X秒内完成,那么过程就会被停止.现在的问题是我的案子还有另一个问题.上面提供的样本并不是单独运行的.它也包含在另一个循环文件中,如下所示:
master.php
<?php
while (1) {
include 'bot.php';
sleep(60);
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到它在无限循环上运行而我想要的并不是停止整个循环而只是"破坏"bot.php循环,保持主while(1)循环活动.使用提供的解决方案,它退出所有循环并终止进程.
PHP不是魔术,不能像那样停止执行脚本.while只有在includes 内的所有处理完成后才会检查该条件.
您可以尝试呼叫register_tick_function()并提供可以检查已过去时间的回调以及exit是否需要.
现在有更多的例子!
<?php
declare(ticks=1);
define('START_TIME', time());
// lambda uses START_TIME constant
register_tick_function(function() {
if (time() - START_TIME > 20) {
echo 'Script execution halted. Took more than 20 seconds to execute';
exit(1);
}
}, true);
include_once 'onefile.php';
include 'somefile.php';
include 'somefile2.php';
?>
Run Code Online (Sandbox Code Playgroud)
这将停止在tick20秒标记后发生的下一次,而不是20秒.
根据您当前的更新编辑#2工作代码
此代码的工作原理类似,但它不会停止脚本执行,而是抛出一个TimeLimitException然后用于跳转到执行点的代码goto.这很hacky,但它可以满足你的需求.
<?php
declare(ticks=1);
$start_time = time();
class TimeLimitException extends Exception {}
// lambda uses $start_time global so it can reset
// the timer after the time limit is reached
register_tick_function(function() {
global $start_time;
if (time() - $start_time > 20) {
echo 'Script execution halted. Took more than 20 seconds to execute', PHP_EOL;
$start_time = time();
throw new TimeLimitException();
}
}, true);
try {
// time limit will reset to here. Cannot jump to a label in a loop
limit:
while (1) {
sleep(1);
echo 'outer ';
while (1) {
echo 'inner ';
sleep(2);
}
}
} catch (TimeLimitException $e) {
echo 'time limit hit, jumping to label `limit`', PHP_EOL;
goto limit;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
493 次 |
| 最近记录: |