Search code examples
pythonrabbitmqpika

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?


Solution

  • 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.