Michal Checinski

Sending delayed messages to Azure Service Bus

February 13, 2019 , posted under Azure
Sending delayed messages to Azure Service Bus

When working with Azure Service Bus I was wondering if I can send delayed messages to Service Bus Queues. It will decrease the calls count for Azure Functions and simplify the whole solution’s architecture. Yes you can (of course). It is simply setting the ScheduledEnqueueTimeUtc propertis in Microsoft.Azure.ServiceBus.Message class. Making an example delayed message looks as follows:

string message = "Delayed message";
Message queueMessage = new Message(Encoding.UTF8.GetBytes(message));

// 5 minute delay:
queueMessage.ScheduledEnqueueTimeUtc = DateTime.UtcNow.AddMinutes(5);

// 30 seconds delay:
queueMessage.ScheduledEnqueueTimeUtc = DateTime.UtcNow.AddSeconds(30);


To simplify my work with I’ve created small helper class with method to send messages to Azure Service Bus:

WARNING If you want to send only one message to particular queue those methods are great. But. If you need to send a lot of messages to one queue it will be better to pass instance of QueueClient class to each and every method call. In that case you do not want to close session (so do not call QueueClient.CloseAsync() method).