php,如何为消费者创建/保持服务在后台? [英] php, how to create/keep service in background, for consumer?

查看:21
本文介绍了php,如何为消费者创建/保持服务在后台?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ubuntu 12.04 运行 ec2 实例.

im running an ec2 instance, with ubuntu 12.04.

我正在使用 aws 基础结构,现在我正在尝试实现一个消费者工作者,它将消耗一个 sqs 队列(消息队列,不是很重要).

i am using aws infastructure, and right now im trying to implement a consumer worker which will consume an sqs queue (queue of msgs, not very important).

为此,我创建了一个 php 文件,它收集"队列 30 秒.最重要的是,我有一个 crontab 每 30 秒运行一次此页面.

to do that i created a php file, which "harvest" the queue for 30 seconds. on top i have a crontab running this page every 30 seconds.

什么是更优雅/更合适的解决方案?我如何制作后台 php 进程,以及如何检查它是否活着,并在需要时杀死它重新启动它?

what is a more elegant/proper solution? how do i make a background php proccess, and how i do check if its alive, and kill it restart it, if needed?

  • 只是澄清一下 - 我问的是消耗队列的过程,无论选择哪个/什么机制(sqs,rabbitMQ)

感谢您的帮助

推荐答案

利用类进程(我从 php 文档中复制)创建一个监视器脚本,如果进程没有运行,它会启动您的工作脚本.监控脚本可以将 pid 保存在一个文件中.

create a monitor script utilizing the class process (which i copied from php docs), which launches your worker script if the process is not running. the monitor script can keep the pid in a file.

然后只需将监视器添加到 crontab.

then simply add the monitor to crontab.

class Process{
    private $pid;
    private $command;

    public function __construct($cl=false){
        if ($cl != false){
            $this->command = $cl;
            $this->runCom();
        }
    }
    private function runCom(){
        $command = 'nohup '.$this->command.' > /dev/null 2>&1 & echo $!';
        exec($command ,$op);
        $this->pid = (int)$op[0];
    }

    public function setPid($pid){
        $this->pid = $pid;
    }

    public function getPid(){
        return $this->pid;
    }

    public function status(){
        $command = 'ps -p '.$this->pid;
        exec($command,$op);
        if (!isset($op[1]))return false;
        else return true;
    }

    public function start(){
        if ($this->command != '')$this->runCom();
        else return true;
    }

    public function stop(){
        $command = 'kill '.$this->pid;
        exec($command);
        if ($this->status() == false)return true;
        else return false;
    }
}

这篇关于php,如何为消费者创建/保持服务在后台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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