/** * Shut it down, delete exchanges, queues, close connections and channels */ public function tearDown() { if ($this->ch) { $this->ch->exchange_delete($this->exchange); $this->ch->queue_delete($this->queue); $this->ch->close(); } if ($this->conn) { $this->conn->close(); } }
/** * Signal to the emitter of the message that we finished. * * @param string $exchange * @param string $queue * @param string $messageContent Message to send to the dispatcher. * * @return bool */ protected function notifyDispatcher($exchange, $queue, $messageContent) { // We put in the queue that we finished $this->channel->basic_publish(new AMQPMessage($messageContent), $exchange); // Read the first message coming out of the queue $message = $this->waitForMessage($queue, 0.5); if (!$message) { // Shouldn't happen -> error while delivering messages? return false; } // If the first message of the queue is our message, we can die in peace // (else it would be the "timeout" message from the dispatcher) $dispatcherNotified = $message->body == $messageContent; // Delete our queue $this->channel->queue_delete($queue); return $dispatcherNotified; }
private function waitForTask($timeout, $exchange, $queue, callable $completed = null, callable $timedout = null, callable $errored = null) { // Wait X seconds for the task to be finished $message = $this->waitForMessage($queue, $timeout); // No response from the worker (the task is not finished) if (!$message) { // We put in the queue that we timed out $this->channel->basic_publish(new AMQPMessage('timeout'), $exchange); // Read the first message coming out of the queue $message = $this->waitForMessage($queue, 0.5); if (!$message) { // Shouldn't happen -> error while delivering messages? return; } } // If the first message of the queue is a "finished" message from the worker if ($message->body == 'finished') { if ($completed !== null) { call_user_func($completed); } // Delete the temporary exchange $this->channel->exchange_delete($exchange); } // If the first message of the queue is a "errored" message from the worker if ($message->body == 'errored') { if ($errored !== null) { $e = new \RuntimeException("An error occured in the background task"); call_user_func($errored, $e); } // Delete the temporary exchange $this->channel->exchange_delete($exchange); } // If the first message of the queue is our "timeout" message if ($message->body == 'timeout') { if ($timedout !== null) { call_user_func($timedout); } // Do not delete the temp exchange: still used by the worker } // Delete the temporary queue $this->channel->queue_delete($queue); }