Scheduling

Component: NServiceBus | Nuget: NServiceBus (Version: 5.x)

This sample illustrates a simple use of the Scheduling 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.

Edit
public class ScheduleStarter :
    IWantToRunWhenConfigurationIsComplete
{
    static ILog log = LogManager.GetLogger<ScheduleStarter>();
    Schedule schedule;
    IBus bus;

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

    public void Run(Configure config)
    {
        // Send a message every 5 seconds
        schedule.Every(
            timeSpan: TimeSpan.FromSeconds(5),
            task: () =>
            {
                var message = new MyMessage();
                bus.SendLocal(message);
            });

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

Related Articles

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

Last modified