【问题标题】:Long running background process in PHP on windows machineWindows机器上PHP中长时间运行的后台进程
【发布时间】:2023-03-28 15:45:01
【问题描述】:

我在 PHP 中有一个脚本,它使用 Curl 逐个点击一长串 URL,并在最后将响应写入文件,我希望从浏览器上传列表并在背景(不让用户等待响应)。我已经尝试了以下解决方案 -

    $command = "C:\wamp\bin\php\php5.5.12\php.exe ../background_process/subscribe_bg.php ".$file_temp_path;
    shell_exec(sprintf('%s > /dev/null 2>/dev/null &', $command));

这会成功运行脚本,但会让浏览器等待。 (这可能会在 Linux 机器的后台运行。)

    $command = "C:\wamp\bin\php\php5.5.12\php.exe ../background_process/subscribe_bg.php ".$file_temp_path;

    execInBackground($command);

    function execInBackground($cmd) { 
        if (substr(php_uname(), 0, 7) == "Windows"){ 
            pclose(popen("start /B ". $cmd, "r"));  
        } 
        else { 
            exec($cmd . " > /dev/null &");   
        } 
    }

我找到了这个适用于 windows 机器的解决方案,但对我不起作用。脚本根本不执行。

请建议在 Windows 机器上使用 PHP 在后台运行长进程(不是很长 ~ 30-40 分钟)的最佳实践。

【问题讨论】:

  • 谢谢你,sainiankit。这一行: pclose(popen("start /B". $cmd, "r"));为我工作。我在 Windows 7 上运行 PHP 5.3。
  • The script does not execute at all. - 实际上它会,但只要父进程(http请求)完成它就会死掉。 background job implementation(或在紧要关头 forking)过于宽泛,无法在 Stackoverflow 上进行描述 - 但这正是您所要求的。

标签: php background-process asynchronous


【解决方案1】:

这非常适用于 Windows 机器,脚本的所有输出都写入 $response_file_path -

$command = $PHP_DIR." ../background_process/subscribe_bg.php -p=".$file_path_arg." >../sublogs/responses/".$file_response_path." 2>../sublogs/error_logs/err.txt";

execInBackground($command)

function execInBackground($cmd) {
    if (substr(php_uname(), 0, 7) == "Windows"){
        pclose(popen("start /B ". $cmd, "r"));
        return 1;
    }
    else {
        return 0;
        //Or the code for linux machine.
    }
}

【讨论】:

  • 正是我的意思。它以前不起作用,因为您的初始命令没有将输出重定向到文件中)))谢谢。
  • 哦,是的!没错,这使浏览器等待该过程完成。
【解决方案2】:

我认为您应该将后台进程的输出重定向到另一个文件。由于您没有重定向它,PHP 正在等待它。将“>”重定向添加到您的命令:

$command = "C:\wamp\bin\php\php5.5.12\php.exe ../background_process/subscribe_bg.php ".$file_temp_path . " > out.log ";

祝你好运! 丹尼洛

【讨论】:

    猜你喜欢
    • 2013-11-23
    • 2011-01-05
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 2016-11-17
    • 1970-01-01
    • 2015-02-14
    • 2012-01-14
    相关资源
    最近更新 更多