Messages don't need to be dispatched immediately. Delayed delivery is a feature that sends messages into the future to be delivered and processed at a later time.
Delayed delivery is used for:
- Timeout messages sent by sagas
- Delayed retries, to retry a message after successive delays when immediate retries don't result in successful processing
- Explicitly sending a message with a delay, as described below
Delaying a message is done using
SendOptions and the
DelayDeliveryWith method. This allows to defer the sending of a message to any endpoint. The behavior of delayed handling using
DelayDeliveryWith can be seen in Delayed Delivery Sample.
Delays delivery of a message for a specified duration.
var sendOptions = new SendOptions(); sendOptions.DelayDeliveryWith(TimeSpan.FromMinutes(30)); await handlerContext.Send(new MessageToBeSentLater(), sendOptions) .ConfigureAwait(false); // OR await endpoint.Send(new MessageToBeSentLater(), sendOptions, handlerContext.CancellationToken) .ConfigureAwait(false);
Delays delivery of a message until a specified point in time.
var options = new SendOptions(); options.DoNotDeliverBefore(new DateTime(2016, 12, 25)); await handlerContext.Send(new MessageToBeSentLater(), options) .ConfigureAwait(false); // OR await endpoint.Send(new MessageToBeSentLater(), options, handlerContext.CancellationToken) .ConfigureAwait(false);
Delayed delivery of messages is supported when one of the following requirements are met:
- The transport supports delayed delivery natively.
- The Timeout Manager feature is enabled and the endpoint is not a send-only endpoint.
When deferring a message, it is sent to the Timeout Manager requesting it to deliver the message at a later time or deferred by using the transports native capability to defer messages.
NServiceBus provides delayed delivery feature for transports that don't have native support for delayed message delivery. All Transports except MSMQ support delayed message delivery natively and therefore don't require persistence to store timeouts. To learn more about NServiceBus delayed message store refer to the Timeout Manager article.