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

心靈之曲
发布: 2024-09-25 20:21:01
转载
332人浏览过

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

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

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
相关标签:
php
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号