php,如何在后台为消费者创建/保持服务?

im running an ec2 instance, with ubuntu 12.04.

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).

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.

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?

  • just a clarification - i am asking about the process which consumes the queue, regardless of which/what mechanizem is selected (sqs, rabbitMQ)

thanks for your help

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.

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;
    }
}

I would suggest RabbitMQ (GitHub). It's a complete and highly reliable enterprise messaging system based on the emerging standard. Check their examples here.

RabbitMQ Manager