|
HTTP 连接关闭 |
简单后台任务 |
无需额外扩展 |
依赖 FPM,长时任务不稳定 |
在API执行的过程,经常遇到要进行大量计算,这种情况对方HTTP超时设置值太小会导致回调数据失败,那么我们这个时候就需要将回调的数据优先输出,然后后台继续执行尚未执行的PHP代码,这样就完美解决了这个问题,当然 set_time_limit(0); 这里建议不要设置为0,可以设置为360秒结束,在遇到代码无限循环错误的时候,可以防止资源占用异常,并在系统日志里得到结果!
use think\Log;
public function asynctask()
{
// 1. 返回响应给前端
$response = ['code' => 0, 'msg' => '任务已开始'];
header('Content-Type: application/json');
header('Connection: close');
// 使用FastAdmin内置响应方法替代原生header
\think\Response::create($response, 'json', 200)->send();
// 2. 后台继续执行(FastAdmin 环境)
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request(); // FPM 环境下立即关闭连接
}
// 3. 执行耗时任务
ignore_user_abort(true);
set_time_limit(0); // 取消超时限制
try {
$this->longRunningTask();
\think\Log::error('后台任务成功完成'); // 记录成功日志
} catch (\Exception $e) {
\think\Log::error('后台任务失败: '.$e->getMessage()); // 记录错误日志
}
}
private function longRunningTask()
{
// 添加任务进度跟踪
$startTime = microtime(true);
// 模拟分阶段执行(替代单次sleep)
for ($i = 1; $i <= 100; $i++) {
// 实际业务操作(如生成报告分页/批量数据处理)
sleep(1);
// 记录阶段日志
\think\Log::error("任务进度: {$i}/10");
}
// 性能监控
$duration = round(microtime(true) - $startTime, 2);
\think\Log::error("任务耗时: {$duration}秒");
}
1210

被折叠的 条评论
为什么被折叠?



