Phil S
Phil S

Reputation: 846

Scheduled Publish in Mass Transit

I'm using Mass Transit with .NET Core 3.1 and Azure Service Bus.

I want to make use of Service Bus's Scheduled Delivery feature when publishing messages to a topic. AZSB seems to support this just fine, but I'm having problems trying to get MT to do it's bit.

I have previously sent scheduled messages successfully to a queue, but want to move to using pub/sub instead. This is the initial send, so not inside a consumer context.

I have now reached the point where I have 'schedule published' a message, it has the correct ScheduledTime attribute on the message, and the Message types is "urn:message:MassTransit.Scheduling:ScheduledMessage".

However, the messages go straight into the subscription for immediate delivery, instead of being scheduled within the topic.

Here is my code:

    private async Task<Result> PublishScheduledMessage(MyTask message, DateTime scheduledDelivery)
    {
        try
        {
            var endpoint = await _bus.GetPublishSendEndpoint<MyTask>();
            await _bus.SchedulePublish<ScheduledMessage>(endpoint, scheduledDelivery, message);
            return Result.Success();
        }
        catch (MassTransitException e)
        {
            _logger.Error(e, $"Error while trying to send scheduled MyTask.  Exception: {e.Message}");
            return Result.Failure(e.Message);
        }
    }

(I also tried publishing MyTask type instead of ScheduledMessage, but no difference)

The only docs I could find on this were here. However, the scheduler interface has no Publish interface, only send, so will only deliver to queues it seems? Does SchedulePublish only work with Rabbit and Quartz?

Can anyone help please?

Upvotes: 1

Views: 5162

Answers (1)

Chris Patterson
Chris Patterson

Reputation: 33278

First, MassTransit v7 has SchedulePublish built into IMessageScheduler, so you can use that once you upgrade.

In the meantime, and because you're using Azure Service Bus, you can schedule a publish easily by just setting the ScheduledEnqueueTime when publishing, as shown below (using the extension method).

bus.Publish<MyTask>(message, context =>
    context.SetScheduledEnqueueTime(delay));

That will set the property for you, which will delay the message until the scheduled time. Basically, the same thing that the scheduler is doing.

When you're scheduling messages using Azure Service Bus (and not using Quartz or Hangfire), you don't use the ScheduleMessage types at all, those are only used for the external message schedulers.

Upvotes: 2

Related Questions