5

AMQP function consume() is a blocking function with a callback, Is it possible to set a timeout for consume() function, so after specific amount of time it doesn't block anymore and the code execution completes ?

AhlyM
  • 510
  • 1
  • 6
  • 16

1 Answers1

6

Yes, here's how:

$amqp = new AMQPConnection($your_connection_params);
$amqp->setTimeout($seconds);

Then when you call consume() on a queue, if no messages arrive within the timeout period, an AMQPException will be thrown from consume() with the message, "Resource temporarily unavailable". If you ever break out of consume() or hit a timeout, be sure to call cancel() on the queue object to properly reset the consumer. In order to do this, you need to generate a globally unique consumer tag and pass it in as an undocumented, third parameter to consume:

$tag = uniqid() . microtime(true);
$queue->consume($callback, $flags, $tag);
$queue->cancel($tag);

That way, you can call consume() again later without weird issues that will make your head spin.

gurumike
  • 106
  • 1
  • 5
  • 1
    FYI, I'm using the pecl amqp module, version 1.0.9. I tried upgrading to the latest version recently and my code completely broke. But the method I described above is working properly with amqp-1.0.9 and rabbitmq 3.1.3. – gurumike Aug 13 '13 at 21:03
  • 2
    Ran into this scenario today and your answer lead me in the right direction. The `setTimeout` method has been deprecated in favour of the `setReadTimeout`. Also make sure to capture the `AMQPConnectionException` exception that consume throws when you timeout. AMQP version 1.4 – JohnP May 21 '15 at 19:47