请求启动后台php脚本

时间:2018-07-06 09:57:42

标签: php apache

我目前正在内部网站上显示大量统计信息,并且由于大数据,某些页面或Ajax脚本非常慢。

我要搜索的是一种通过请求在后台启动这些脚本,然后启动ajax请求以了解后台脚本进度的方法。

有什么办法可以做到这一点?我使用php7.0和apache2服务器(我无法直接访问apache服务器配置,因此,如果可能,我会搜索客户端选项)

2 个答案:

答案 0 :(得分:0)

如果有人在寻找实现此目标的方法,这是我找到的解决方案:

我在Ajax中调用一个脚本,该脚本将自身进行分叉并将子进程的PID保存在数据库中。 然后,我在子进程中调用session_write_close()以允许用户发出新请求,然后父进程退出(不等待子进程结束)。 父亲离开后,用户会收到对他的请求的答复,子进程将继续他的工作。

然后在Ajax中,我调用另一个脚本来获取worker的进化,最后我得到结果并在完成所有步骤后杀死子进程。

这是我的工人班级的代码:

class AsyncWorker
{
    private $pid;
    private $worker;

    private $wMgr;

    public function __construct($action, $content, $params = NULL)
    {
        $this->wMgr   = new WorkersManager();
        $pid = pcntl_fork(); // Process Fork
        if ($pid < 0) {
            Ajax::Response(AJX_ERR, "Impossible de fork le processus");
        } else if ($pid == 0) { // In the child, we start the job and save the worker properties
            sleep(1);
            $this->pid    = getmypid();
            $this->worker = $this->wMgr->fetchBy(array("pid" => $this->pid));
            if (!$this->worker) {
                $this->worker = $this->wMgr->getEmptyObject();
                $this->wMgr->create($this->worker);
            }
            $this->worker->setPid($this->pid);
            $this->worker->setAction($action);
            $this->worker->setContent($content);
            $this->worker->setPercent(0.00);
            $this->worker->setResult("");
            $this->wMgr->update($this->worker);
            $this->launch($params);
        } else { // In the father, we save the pid to DB and answer the request.
            $this->worker = $this->wMgr->fetchBy(array("pid" => $this->pid));
            if (!$this->worker) {
                $this->worker = $this->wMgr->getEmptyObject();
                $this->worker->setPid($pid);
                $this->wMgr->create($this->worker);
            }
            Ajax::Response(AJX_OK, "Worker started", $this->worker->getId());
        }
    }

    // Worker job
    private function launch($params = NULL)
    {
        global $form, $_PHPPATH, $url, $session;
        session_write_close(); // This is useful to let the user make new requests
        ob_start(); // Avoid writing anything

        /*
        ** Some stuff specific to my app (include the worker files, etc..)
        */            

        $result = ob_get_contents(); // Get the wrote things and save them to DB as result
        $this->worker->setResult($result);
        $this->worker->setPercent(100);
        ob_end_clean();
    }
}

这有点棘手,但是我别无选择,因为我无法访问服务器插件和库。

答案 1 :(得分:-1)

您可以使php脚本执行shell bash脚本,或为此使用exec()方法