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

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

任何处理过导入或导出数据的人都可能遇到过脚本执行时间限制很短的问题。最快的解决方案通常涉及调整 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 secondswhile (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 端点的连接、关闭文件或执行其他操作,则必须记住添加此时间。

以上就是针对最大执行时间限制的基本保护的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1247455.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
掌握 PHP 中的简洁代码:我的编码之旅的主要经验教训
上一篇 2025年12月9日 19:29:50
在 PHP 中构建 Pawn 到 Python 编译器
下一篇 2025年12月9日 19:29:57

相关推荐

发表回复

登录后才能评论
关注微信