php - 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 将在我的项目文件夹中创建文件。
我怎么解决这个问题 ?
解决方案
尝试改变:
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
这样您就可以更轻松地调试
推荐阅读
- node.js - 架构中的属性值采用默认值而不是 MongoDB/Mongoose 中定义的值
- matlab - 在 Matlab 中通过重建进行形态闭合
- reactjs - 在项目中使用两个不同的 React/React-Dom 版本
- google-api - 无法获取 Chrome Web Store API 的刷新令牌以发布 Chrome 扩展
- ionic-framework - 打包安卓。support.v4.content 不存在
- r - 计算不同日期同一时间的平均值
- ios - 目前无法安装此应用 Xcode 11
- php - 卸载shopify应用任何回调或设置
- python - 当方法被孩子覆盖时,在 super().__init__ 中调用父方法
- python - DisallowedRedirect:使用协议“127.0.0.1”不安全重定向到 URL