'How to check the Azure Service Bus queue is empty?

I'm using azure service bus queues in my application and here my question is, is there a way how to check the message queue is empty so that I can shutdown my containers and vms to save cost. If there is way to get that please let me know, preferably in python.

Thanks



Solution 1:[1]

For this, you can use Azure Service Bus Python SDK. What you would need to do is get the properties of a queue using get_queue method that will return an object of type Queue. This object exposes the total number of messages through message_count property. Please note that this count will include count for active messages, dead-letter queue messages and more.

Here's a sample code to do so:

from azure.servicebus import ServiceBusService, Message, Queue
bus_service = ServiceBusService(
    service_namespace='namespacename',
    shared_access_key_name='RootManageSharedAccessKey',
    shared_access_key_value='accesskey')
queue = bus_service.get_queue('taskqueue1')
print queue.message_count

Source code for Azure Service Bus SDK for Python is available on Github: https://github.com/Azure/azure-sdk-for-python/tree/master/azure-servicebus/azure/servicebus.

Solution 2:[2]

You could check the length of the messages returned from peek_messages method on the class azure.servicebus.ServiceBusReceiver

with servicebus_receiver:
    messages = servicebus_receiver.peek_messages(max_message_count=1)
if len(messages) == 0:
    print('Queue empty')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gaurav Mantri
Solution 2 aless80