针对最大执行时间限制的基本保护

Susan Sarandon
发布: 2024-09-25 20:10:02
原创
520 人浏览过

Basic Protection Against Max Execution Time Limit

任何处理过导入或导出数据的人都可能遇到过脚本执行时间限制过短的问题。最快的解决方案通常涉及调整 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中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!