AI agents: use the documentation index at llms.txt to locate machine-readable pages. This section is indexed by https://docs.particular.net/samples/llms.txt. The markdown version of this page is served as plain text. An MCP server at /mcp serves the same content via the search_docs and read_doc tools; it is read-only and needs no credentials. Markdown versions of documentation pages are available by appending .md to the page URL. Directory URLs use index.md. They are served as text/plain because some retrieval backends reject text/markdown.

PeriodTimer usage

Component:
NServiceBus
NuGet Package:
NServiceBus 10.x

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.Services.AddNServiceBusEndpoint(endpointConfig);

builder.Services.AddHostedService<SendMessageJob>();

Related Articles

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