Getting Started
Architecture
NServiceBus
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Samples

PeriodTimer usage

This sample illustrates the use of PeriodicTimer to send messages from within an NServiceBus endpoint.

PeriodicTimer was introduced in .NET 6 and enables waiting asynchronously for timer ticks.

Running the project

  1. Start both the Scheduler and Receiver projects.
  2. At startup, Scheduler will schedule a message send to Receiver every 3 seconds.
  3. Receiver will handle the message.

Code Walk-through

Define the background service

The BackgroundService defines the job to be run when the host starts. It sets up a PeriodicTimer which will tick every 3 seconds. Every time it ticks, a message is sent using NServiceBus.

class SendMessageJob(IMessageSession messageSession) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using var timer = new PeriodicTimer(TimeSpan.FromSeconds(3));

        while (await timer.WaitForNextTickAsync(stoppingToken))
        {
            await messageSession.Send("Receiver", new MyMessage(), stoppingToken);
        }
    }
}

Configure host

The host is configured with NServiceBus and the background service created above. When the host starts, the background service is run and messages will be sent periodically.

var builder = Host.CreateApplicationBuilder();

var endpointConfig = new EndpointConfiguration("Scheduler");
endpointConfig.UseTransport(new LearningTransport());
endpointConfig.UseSerialization<SystemJsonSerializer>();

builder.UseNServiceBus(endpointConfig);

builder.Services.AddHostedService<SendMessageJob>();

Related Articles

  • Scheduling
    Schedule a task or an action/lambda, to be executed repeatedly at a given interval.