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