Pranjal Chandel
Pranjal Chandel

Reputation: 11

How to stop consumer in Rabbit MQ once the message queue is empty in pika library?

So i am basically trying to send some message from a producer to consumer in RabbitMQ using python client (Pika Library) but by default receiver keeps on running even after reading the message because it waits for further messages but what i want according to my requirement that the receiver should stop once after it reads all the messages from the queue and basically when the queue is empty or atleast it should read messages one by one and when i turn it on again or after a defined period it should read the messages again but the main concern is to stop the receiver. So how can i do that in python's pika library.

Upvotes: 1

Views: 1727

Answers (1)

Luke Bakken
Luke Bakken

Reputation: 9627

the receiver should stop once after it reads all the messages from the queue and basically when the queue is empty

Since queues can always be published to, are they ever really "empty"? You need to come up with a condition that defines "empty", something like "has not had a message within the last 5 seconds" or "consumer saw a particular STOP message".

I recently answered a similar question:

Closing idle consumer which handles long running task in rabbitmq pika

Please see this code, which demonstrates a consumer that stops after 5 seconds of inactivity:

https://github.com/lukebakken/so-pika-idle-consumer-72792217/blob/master/consumer.py

Upvotes: 1

Related Questions