針對最大執行時間限制的基本保護

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學習者快速成長!