Scheduler

Component: NServiceBus
NuGet Package NServiceBus (5.x)

This sample illustrates a simple use of the Scheduler API. Two common use cases are shown

  1. Sending a message.
  2. Executing some custom code.

The scheduling API is accessed via a dependency injected instance of the Schedule class. In this case running at startup by implementing IWantToRunWhenConfigurationIsComplete.

public class ScheduleStarter :
    IWantToRunWhenBusStartsAndStops
{
    static ILog log = LogManager.GetLogger<ScheduleStarter>();

    IBus bus;
    Schedule schedule;

    public ScheduleStarter(Schedule schedule, IBus bus)
    {
        this.schedule = schedule;
        this.bus = bus;
    }

    public void Start()
    {
        // Send a message every 5 seconds
        schedule.Every(
            TimeSpan.FromSeconds(5),
            () =>
            {
                var message = new MyMessage();
                bus.SendLocal(message);
            });

        // Name a schedule task and invoke it every 5 seconds
        schedule.Every(
            TimeSpan.FromSeconds(5),
            "MyCustomTask",
            () => { log.Info("Custom Task executed"); });
    }

    public void Stop()
    {
        //no-op
    }
}

Related Articles

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

Last modified