首页 > 解决方案 > PHP 如何执行后台任务?

问题描述

为了尝试背景测试,我创建了 3 个文件:

Index.html(负责通过ajax调用一个php文件)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Background Task Manager</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>

Press The Button To execute a Background Task...
<br>
<button id="perform">Perform Task</button>

</body>

<script>

$( document ).ready(function() {

    $( "#perform" ).click(function() {
      submitAjax();
    });

    function submitAjax() {
            $.ajax({
                url: 'test.php',
                type: "post",
                data: '',
                success: function (data) {
                    alert(data);
                }
            });
        }

});

</script>

</html>

Test.php(使用后台方法调用另一个文件的文件)

<?php

//Perform Background Task

exec("C:/wamp/bin/php/php5.6.35/php.exe C:/wamp/www/background/file.php");

echo "Process Started";

?>

File.php(将在后台执行的文件)

<?php

//Create a File

sleep(20);

$content = "My Text File";
$fp = fopen("myText.txt","wb");
fwrite($fp,$content);
fclose($fp);

echo "File Created...";

?>

想法如下:一旦用户单击按钮,就会向 test.php 文件发出请求。test.php 将触发对 file.php 的后台请求,消息('Process Started')将立即出现,并且在我的项目文件夹中创建文件后 20 秒。

发生了什么:当用户单击按钮时,我仅在 20 秒后收到消息“进程已启动”,即请求不是在后台模式下发出的。

我希望发生的事情:当用户单击按钮时,将立即出现“进程已启动”消息,20 秒后 php 将在我的项目文件夹中创建文件。

我怎么解决这个问题 ?

标签: phpexecbackground-process

解决方案


尝试改变:

exec("C:/wamp/bin/php/php5.6.35/php.exe C:/wamp/www/background/file.php");
echo "Process Started";

至:

ob_start();
echo "Process Started";
ob_end_flush();
ob_flush();
flush();
exec("C:/wamp/bin/php/php5.6.35/php.exe C:/wamp/www/background/file.php");

您的问题的相关答案: 发送 http 响应后继续处理 php

你也可以使用include而不是使用exec() 它,就像:

start();
echo "Process Started";
ob_end_flush();
ob_flush();
flush();

include 'background/file.php';

file.php这样您就可以更轻松地调试


推荐阅读