PHP RabbitMQ setTimeout or other option to stop waiting for queue

jedi picture jedi · Nov 26, 2015 · Viewed 9.1k times · Source

I'm required to create a simple queue manager to pass a number from a sender to a consumer. Hello World tutorial provided by RabbitMQ covers almost 70% of it.

But I need to change the queue to not to forever waiting for incoming messages. Or stop waiting after certain amount of messages. I read and tried few solutions from other post, but it doesn't work.

rabbitmq AMQP::consume() - undefined method. there's another method, wait_frame but it is protected.

and other post is in python which I dont understand.

<?php

require_once __DIR__ . '/vendor/autoload.php';
require 'config.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;

function recieveQueue($queueName){
    $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');

    // try{
    //  $connection->wait_frame(10);
    // }catch(AMQPConnectionException $e){
    //  echo "asdasd";
    // }

    $channel = $connection->channel();

    $channel->queue_declare($queueName, false, false, false, false);

    echo ' [*] Waiting for messages. To exit press CTRL+C', "\n";

    $callback = function($msg) {
        echo " [x] Received ", $msg->body, "\n";

    };

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

    $channel->basic_consume($queueName, '', false, true, false, false, $callback);

    // $channel->cancel($tag);

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

    echo "\nfinish";
}

recieveQueue('vtiger');

?>

Answer

Nick picture Nick · Nov 26, 2015

Modify wait() in while loop:

$timeout = 55;
while(count($channel->callbacks)) {
    $channel->wait(null, false, $timeout);
}