0

Need help please.

How do I stop running Python code once there are no more messages in the queue?

Tried the following but doesn't seem to be working.

   import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()


# callback function on receiving messages
def onMessage(channel, method, properties, body):
    bodyMsg = body
    print(bodyMsg)
    return body


def Consume(queuename):
    try:
        channel.basic_consume(on_message_callback=onMessage, queue=queuename, auto_ack=True)
        q = channel.queue_declare(queue='hello')
        q_len = q.method.message_count
        channel.start_consuming()
    finally:
        stop_consuming()


# connect credentials = pika.PlainCredentials(username, password) connection = pika.BlockingConnection(
# pika.ConnectionParameters(host = server, port = port, virtual_host = vhost, credentials = credentials))
def stop_consuming(self):
    #  """Tell RabbitMQ that you would like to stop consuming by sending the
    #  Basic.Cancel RPC command.
    if self._channel:
        print('Sending a Basic.Cancel RPC command to RabbitMQ')
        self._channel.basic_cancel(self.on_cancelok, self._consumer_tag)


Consume('hello')

Thanks

lola
  • 9
  • 4

1 Answers1

0

It is a bit unclear whether you want to stop consuming when there are no messages or if you want to stop the application.

First, you need to know if there are messages left in the queue.

I can't test if this works, but there's an answer here: Getting number of messages in a RabbitMQ queue.

Then, after each message which triggers the handler, you can check if there are messages left. If for example it states that there are 7 messages left, you could check again after 7 messages to make it a bit more efficient (this only works if you know how many consumers you'd have). Otherwise you should check it every time after a message is consumed.

If the message count is 0, you can stop the application/stop consuming the queue.

Jordy
  • 320
  • 2
  • 15
  • Thanks. I want to stop the application. I tried according to the link you posted but I get the error: receivemq is not allowed to run in parallel if cnt > 0: self.channel.basic_consume( queue=self.callback_queue, on_message_callback=self.on_response, auto_ack=True) print('count' + str(cnt)) else: self.channel.stop_consuming() – lola Sep 12 '22 at 09:30