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

查看:125
本文介绍了在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. 对'../blah/generate-report'进行ajax调用并立即返回
  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天全站免登陆