Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I schedule a task to run each day using NServiceBus

Is there a elegant way of scheduling tasks using NServiceBus. There is one way I found while searching the net. Does NServiceBus give internal APIs for scheduling.

like image 679
frictionlesspulley Avatar asked Jul 19 '11 20:07

frictionlesspulley


2 Answers

NServiceBus now has this built in

From here http://docs.particular.net/nservicebus/scheduling-with-nservicebus

public class ScheduleStartUpTasks : IWantToRunWhenTheBusStarts
{
    public void Run()
    {
        Schedule.Every(TimeSpan.FromMinutes(5)).Action(() =>
            Console.WriteLine("Another 5 minutes have elapsed."));

        Schedule.Every(TimeSpan.FromMinutes(3)).Action(
                            "MyTaskName",() =>
                            { 
                                Console.WriteLine("This will be logged under MyTaskName’.");
                            });
    }
}

Note the caveat

When not to use it. You can look at a scheduled task as a simple never ending saga. But as soon as your task starts to get some logic (if-/switch-statements) you should consider moving to a saga.

like image 54
Simon Avatar answered Oct 25 '22 10:10

Simon


Note: This answer was valid for NServiceBus Version 2.0, but is correct no longer. Version 3 has this functionality. Go read Simon's answer, it is valid for Version 3!

NServiceBus does not have a built-in scheduling system. It is (at a very simple level) a message processor.

You can create a class that implements IWantToRunAtStartup (Run and Stop methods) and from there, create a timer or do whatever logic you need to do to drop messages onto the bus at certain times.

Other people have used Quartz.NET together with NServiceBus to get more granular scheduling functionality.

like image 3
David Boike Avatar answered Oct 25 '22 11:10

David Boike