
任何处理过导入或导出数据的人都可能遇到过脚本执行时间限制很短的问题。最快的解决方案通常涉及调整 php 配置或完全禁用脚本开头的限制。然而,显着延长执行时间或完全禁用它会带来安全风险。无法停止的后台脚本可能会导致资源消耗过多。
在迭代中处理任务时,可以及时监控各个阶段并尝试在时间限制到期之前正常终止执行。
// initialize basic variables for further work
$maxexecutiontime = (int)ini_get('max_execution_time');
$estimatecycletime = 0;
$starttime = microtime(true);
// for demonstration purposes, we use an "infinite" loop with a simulated task lasting 10 seconds
while (true) {
sleep(10);
// calculate the current runtime
$currentruntime = microtime(true) - $starttime;
// termination can be done either with a fixed constant
// or by measuring the time of one pass and trying to use
// the longest possible segment of the runtime
// limit (has its problem).
if ($estimatecycletime === 0) {
$estimatecycletime = $currentruntime;
}
// check if the iteration stop time is approaching.
// subtract the time of one pass, which likely won't fit
// within the window.
if (($maxexecutiontime - $estimatecycletime) < $currentruntime) {
echo 'time is end';
break;
}
}
基于一轮计算的提前终止适用于需要在尽可能少的新执行中处理大量轮次的情况,并且一轮中的每个操作同样耗时。如果各个通行证的时间要求不同,则必须在通行证时间上添加一个系数。另一种选择是使用预定义的时间:
$beforeEndTime = 1;
if (($maxExecutionTime - $beforeEndTime) < $currentRunTime) {
echo 'Time is end';
break;
}
如果脚本在迭代后继续,例如关闭与 api 端点的连接、关闭文件或执行其他操作,则必须记住添加此时间。
以上就是针对最大执行时间限制的基本保护的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号