简体   繁体   English

如何在后台执行 PHP 脚本?

[英]How to execute a PHP script in the background?

I have a code script like this:我有一个这样的代码脚本:

public function getList(){

    // codes here

    // One month passed from the last fetch
    if ( true ) {
        $this->doTheJob();
    }

    return $data;
} 

public function doTheJob(){

    sleep(10); // simplified for a google API fetch/crawling

    // Insert something in the database
}

All I want to do is getting the $data quickly when I call getList() .我想做的就是在调用getList()时快速获取$data In other words, I want to return the result immediately without waiting 10 secs.换句话说,我想立即返回结果而无需等待 10 秒。 So I need to call doTheJob() in the background (probably called "parallel process" or "independent process").所以我需要在后台调用doTheJob() (可能称为“并行进程”或“独立进程”)。

Any idea how can I do that?知道我该怎么做吗?

Easiest way should be when you execute your doTheJob() task in a cronjob every N minutes, write the result to a read optimized database projection when getList() calls, read the database projection.最简单的方法应该是每 N 分钟在 cronjob 中执行 doTheJob() 任务,在 getList() 调用时将结果写入读取优化的数据库投影,读取数据库投影。 If you have not problem the data is max N minutes old and its computing a lot, this could work.如果你没有问题,数据最多 N 分钟,并且它的计算量很大,这可以工作。

Another alternative without those drawbacks, but more complex: Setup a rabbitmq service.另一种没有这些缺点但更复杂的替代方案:设置 rabbitmq 服务。 The process which modifies the data saves a "something changed" event to the queue.修改数据的过程将“更改的内容”事件保存到队列中。 Create another php script as a rabbitmq listener which listens to the "something changed" event and then applies the changes to your read optimized database.创建另一个 php 脚本作为 rabbitmq 侦听器,该侦听器侦听“更改的内容”事件,然后将更改应用于读取优化的数据库。 The data will always be updated on time, there is no computing overhead.数据将始终按时更新,没有计算开销。

Rabbitmq Library for php: https://github.com/php-amqplib/php-amqplib php 的 Rabbitmq 库: https://github.com/php-amqplib/php-amqplib

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM