Example #1
0
 function process(Queue $queue)
 {
     if (file_exists($this->pidFile)) {
         $serverPid = trim(file_get_contents($this->pidFile));
         # When the process is not running anymore and a PID file exists
         # than the PID file was not correctly unlinked on the last shutdown.
         if (!posix_kill($serverPid, 0)) {
             unlink($this->pidFile);
         } else {
             throw new UnexpectedValueException("Server is already running with PID {$serverPid}.");
         }
     }
     if (false === @file_put_contents($this->pidFile, posix_getpid())) {
         throw new UnexpectedValueException(sprintf('Could not create %s. Maybe you have no permission to write it.', $this->pidFile));
     }
     $this->selfPipe = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
     $this->queue = $queue;
     $queue->process($this);
     # Spawn up the initial worker pool.
     $this->spawnWorkers();
     register_shutdown_function(array($this, "stopListening"));
     pcntl_signal(SIGTTIN, array($this, "incrementWorkerCount"));
     pcntl_signal(SIGTTOU, array($this, "decrementWorkerCount"));
     pcntl_signal(SIGQUIT, array($this, "shutdown"));
     pcntl_signal(SIGINT, function () {
         exit;
     });
     # Monitor the child processes.
     for (;;) {
         pcntl_signal_dispatch();
         if ($this->shutdown) {
             foreach ($this->workers as $pid => $info) {
                 posix_kill($pid, SIGQUIT);
                 pcntl_waitpid($pid, $procStatus);
             }
             $this->stopListening();
             return;
         }
         $read = array($this->selfPipe[1]);
         $write = null;
         $exception = null;
         $readySize = @stream_select($read, $write, $exception, 10);
         # Handle the heartbeat sent by a worker.
         if ($readySize > 0 and $read) {
             $childPid = trim(fgets($read[0]));
             $this->workers[$childPid]["heartbeat"] = time();
         }
         $this->removeStaleWorkers();
         # Maintain a stable worker count. Compares the actual worker count
         # to the configured worker count and spawns workers when necessary.
         $this->spawnWorkers();
     }
 }
Example #2
0
 function process(Queue $queue)
 {
     $queue->process($this);
     for (;;) {
         $job = $queue->pop();
         if ($job) {
             $this->emit('init', array($job));
             $self = $this;
             set_error_handler(function ($code, $message, $file, $line) use($job, $self) {
                 throw new \ErrorException($message, $code, 0, $file, $line);
             });
             try {
                 $job->run();
                 $this->emit('success', array($job));
             } catch (\Exception $e) {
                 $this->emit('exception', array($job, $e));
             }
             restore_error_handler();
         }
     }
 }