简体   繁体   中英

How to detect when ServiceBus Queue is empty?

I'm using a WebJob to pull from my ServiceBus Queue via the trigger method and it seems to work well. The problem is I have a nightly job that pumps work into a queue, then I'd like to have another job run at the end when the queue work is finally processed to email the results. My WebJob is currently processing 16 items at a time, and I'll probably have to have multiple WebJobs running to handle the load, so I don't feel like I can just check if the Queue is empty on every trigger.

Is there a way the ServiceBus can signal when it's empty? Should I just have another recurring process running that checks every 10 minutes and fires with a daily bit value to make sure it's done? Seems inefficient. Is there some Azure pattern I'm missing here?

Azure Service Bus will not signal about empty queues. Knowing if there are any number of messages in a queue would be probably considered an anti-pattern. As Clemens Vasters said

Anytime any #Azure #ServiceBus client code looks at QueueDescription.MessageCount to determine whether to call Receive - that's a bug. Don't

Queue can contain work items at any point in time. You never know when that will end. If you have messages that represent something as a group and need to trigger an operation at the end of that group processing, you could have something that can track what work has been accomplished and when it's all done, trigger another message. It could be "I've processed X messages for session Y and therefore this work is completed, sending a notification command".

You can do this by using an instance of NamespaceManaager. It gives you the count of messages in the subscription.

NamespaceManager nsManager = NamespaceManager.CreateFromConnectionString(<connectionstring>);
            var subscription = nsManager.GetSubscription(
                <topicName>,<subscriptionName>);
if(subscription != null && subscription.MessageCount > 0)
//do something

If you want to avoid DLQ count then you can use subscription.MessageCountDetails.ActiveMessageCount instead in above code.

As Sean had mentioned, it would be ideal to submit a message to another queue say 'Emails' at the completion of group processing. Create a logic app with a trigger on 'when a new message is received in the 'Emails' queue and action to send out an email to the required recipients. It is pretty easy to achieve this without even a line of code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM