quickshiftin
quickshiftin

Reputation: 69621

PHP Amqp channel callback loop

The example code for RabbitMQ states

Our code will block while our $channel has callbacks. Whenever we receive a message our $callback function will be passed the received message.

With this code snippet

while(count($channel->callbacks)) {
    $channel->wait();
}

This confuses me, because the default timeout for PhpAmqpLib\Channel\AbstractChannel::wait is forever.

public function wait($allowed_methods = null, $non_blocking = false, $timeout = 0)

So if wait blocks forever, how would the code ever reach a second iteration of the while loop?

Would it be safe to say the while loop is only necessary if wait is passed a $timeout > 0?

Upvotes: 1

Views: 1937

Answers (2)

IMSoP
IMSoP

Reputation: 97718

The timeout parameter on the wait call is how long to wait for the next message before giving up. The default value, as you say, is "forever", which means "until a message arrives".

However, once a single message has been received and processed, the wait call exits; it could perhaps be named waitForNextEvent(). You can see that in the source you linked to:

if ($this->should_dispatch_method($allowed_methods, $method_sig)) {
    return $this->dispatch($method_sig, $args, $amqpMessage);
}

So to receive more than one message, you need to call wait() more than once. Generally, in a consumer, you want to call it an infinite number of times, so you could just use while(true), but allowing the loop to exit if you unregister all your callbacks gives you a way of gracefully exiting.

Upvotes: 2

Confidence
Confidence

Reputation: 2303

the code you are showing, would represent the worker or processor of the AMQP messages

Because it will listen for dropped messages from the AMQP server, it will be waiting/listening/looping forever for these messages.

Upvotes: 0

Related Questions