」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在背景中執行耗時的PHP進程,而不會阻止用戶?

如何在背景中執行耗時的PHP進程,而不會阻止用戶?

發佈於2025-03-23
瀏覽:259

How Can I Execute Time-Consuming PHP Processes in the Background Without Blocking the User?

Executing Background Processes in PHP

Executing time-consuming processes, such as directory copying, without stalling the user experience can be a challenge. This article introduces a solution that enables such tasks to run in the background.

Background Process Execution

To initiate a directory copy without user interruption, consider the following steps:

  1. Use exec() to Launch the Command:
    Employ exec to啟動複製命令,將輸出重定向到文件($ outputfile),然後將進程ID附加到另一個文件($ pidfile)。 This ensures continuous monitoring.

    exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));
  2. Monitor Process Status:
    Implement the isRunning function to track the process's status based on its pid。

    函數isRunning($ pid){ 嘗試{ $ result = shell_exec(sprintf(“ ps%d”,$ pid)); if(count(preg_split(“/\ n/”,$ result))> 2){ 返回true; } } catch(異常$ e){} 返回false; } [2
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3