Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a timeout to method start_consuming() on pika library

I have a BlockingConnection, and I follow the examples of pika documentation. But in all of them, the example of code to start consuming messages are:

connection = pika.BlockingConnection()
channel = connection.channel()
channel.basic_consume('test', on_message)
try:
    channel.start_consuming()
except KeyboardInterrupt:
    channel.stop_consuming()
connection.close()

(with more or less details).

I have to code many scripts, and I want to run one after another (for test/research purposes). But the above code require that I added ^C in each one.

I try to add some timeouts explained in the documentation, but I haven't luck. For example, if I find a parameter for set if client don't consuming any message in the last X seconds, then script finish. Is this posible in pika lib? or I have to change the approach?

like image 881
Tuxman Avatar asked Oct 28 '25 03:10

Tuxman


2 Answers

Don't use start_consuming if you don't want your code to block. Either use SelectConnection or this method that uses consume. You can add a timeout to the parameters passed to consume.

like image 121
Luke Bakken Avatar answered Oct 29 '25 23:10

Luke Bakken


It's too late but perhaps someone gets benefited from that. You can use blocked_connection_timeout argument in pika.ConnectionParameters() as follows,

connection = pika.BlockingConnection(
          pika.ConnectionParameters(
            heartbeat=600,
            blocked_connection_timeout=600,
            host=self.queue_host,
            port=constants.RABBTIMQ_PORT,
            virtual_host=self.rabbitmq_virtual_host,
            credentials=pika.PlainCredentials(
              username=self.rabbitmq_username,
              password=self.rabbitmq_password
            )
          )
        )
like image 26
R.Muneeb Avatar answered Oct 29 '25 23:10

R.Muneeb