Application often needs some kind of an event scheduler, which triggers a process in a particular point in time. This schedule must be configurable and could include multiple occurrences in a particular interval.
Luckily, the Azure Service Bus provides the functionality of scheduled-messages
, even in its most basic plan. Based in this, such an event scheduler can be easily implemented with following advantages:
The snippet implements:
PostEventConfig
.HandleTriggerQueueMessage
bases on a Service Bus trigger and is called when the configured due date is reached. It included:
public static async Task ScheduleTrigger(ServiceBusMessage message, DateTimeOffset dueTimestamp, ILogger log, CancellationToken cancellationToken = default)
{
try
{
await using var sender = ServiceBusClient.Value.CreateSender(Configurations.ServiceBusQueueName);
var seqNum = await sender.ScheduleMessageAsync(message, dueTimestamp, cancellationToken);
log.LogInformation($"Trigger scheduled for MessageId {message.MessageId} -> SequenceNumber = {seqNum}");
}
catch (Exception e)
{
log.LogError(e, "Dispatch message to ServiceBus failed");
}
}