Schedule messages on your queue
    • Dark
      Light
    • PDF

    Schedule messages on your queue

    • Dark
      Light
    • PDF

    Article Summary

    #ServerlessTips - Azure Service Bus
    Author: Jan de Vries, Microsoft Azure MVP

    In a distributed environment working with the Azure Service Bus is an excellent idea. It has lots of enterprise features you will like, and it is relatively cheap.

    One handy feature is the option to schedule messages on your queue.

    There are lots of scenarios where you need something to happen at a specific point in time. Most of the time, we resort to using a timer job, like a timer triggered Azure Function. However, you can also use the Service Bus for these kinds of scenarios.

    Using the Service Bus and the Azure Functions Service Bus Trigger, you will not waste any compute resources, like with an Azure Function with a Timer Trigger, if nothing needs to happen. And we all know, saving resources will save you money in the long run.

    So, how to send scheduled messages? Well, it’s very similar compared to sending regular messages. See the code sample below.

    var tokenProvider = TokenProvider.CreateManagedIdentityTokenProvider();
    var queueClient = new QueueClient(endpoint, queueName, tokenProvider);
    var serializedMessage = JsonSerializer.Serialize(message);
    var serviceBusMessage = new Message(Encoding.UTF8.GetBytes(serializedMessage));
    var sequenceNumber = await queueClient.ScheduleMessageAsync(serviceBusMessage, scheduledAt);
    

    It is a good practice to store the returned 'sequenceNumber' somewhere. You need this in case there is a need to remove the scheduled message. Deleting, or rather Cancelling, the scheduled message can be implemented like the following code sample.

    var tokenProvider = TokenProvider.CreateManagedIdentityTokenProvider();
    var queueClient = new QueueClient(endpoint, queueName, tokenProvider);
    await queueClient.CancelScheduledMessageAsync(sequenceNumber);
    

    Also, get insights into Azure Service Bus monitoring on messaging issues and how you can improve them.

    Service Bus-12


    Was this article helpful?