在 php 中为长时间运行的进程创建后台进程 [英] creating background processes in php for long running process

查看:27
本文介绍了在 php 中为长时间运行的进程创建后台进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,如果这是另一个问题的重复,请原谅我,但经过搜索我没有找到明确的答案.我基本上想要做的是让我的 php web 应用程序触发一些事件(如电子邮件或报告生成器),可能需要几分钟才能完成并立即将控制权返回给页面.我来自 .NET 世界,在那里这可以通过线程轻松完成.

Ok so forgive me if this is a repeat of another question, but after searching I have not found a clear answer. What I basically want to do is have my php web application fire off some event (like an emailer or report generator) that may take a few minutes to complete and immediately return control to the page. I come from a .NET world where this can easily be accomplished with a thread.

这里是工作流程:

  1. 用户点击生成报告"按钮
  2. ajax 调用../blah/generate-report"并立即返回
  3. 流程开始并运行直到完成,然后用户可以继续他的业务
  4. 用户可以返回报告页面并查看进度:报告已完成 50%"

实现这一目标的最佳方法是什么?简短的回答很好.我不想要为我编写的代码,只是一些指导.我查看了 shell_exec,但我不确定这是否是最好的方法,或者如果是,如何使用它来处理 Web 应用程序中的函数.(如果这有什么不同,我正在使用 Yii 框架).谢谢.

What's the best way to accomplish this? Brief answers are fine. I don't want code written for me, just some guidance. I looked at shell_exec but I'm not sure exactly if that is the best way or if it is, how to use it to process functions within a web app. (I'm using the Yii framework if that makes any difference). Thanks.

-杰森

推荐答案

我们在这里创建了一个函数,它会向浏览器返回答案并继续执行.我们使用它来发送电子邮件,而无需让用户等待.

We've created a function here that returns an answer to the browser and keeps executing. We use it to send email without making the user wait for it.

public function redirectAndContinue( $url )
{
    ignore_user_abort(true);
    header("Location: $url");
    header("Connection: close");
    header("Content-Length: 0");
    flush();
}

你可以这样使用

// do quick basic stuff to validate your report

$this->redirectAndContinue( $url )

// send your email or do other slow stuff

问题是:它不适用于 AJAX,它必须是常规页面请求(可能带有 POST).但无论如何你都可以制作进度条:在你的数据库或会话中保存一些东西,然后继续调用一些 URL 以通过 AJAX 获取进度.

The problem is: it doesn't work with AJAX, it must be a regular page request (possibly with a POST). But you can make the progress bar anyway: save something in your database or session and then keep calling some URL to get the progress via AJAX.

这篇关于在 php 中为长时间运行的进程创建后台进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆