Thursday, March 28, 2013

Run Multiple Tasks in a Windows Service

ServicesBase.Run(ServiceBase[] services) ...that sure made me think you could run multiple implementations of ServiceBase in a single Windows Service; but that is not how it works.

One Service, Multiple Tasks

I often have a very simple use case: I needed to run multiple tasks in a single windows service. For example, one task to poll some email notifications, and one task to listen to HTTP requests that might trigger those same notifications.

I like the basic setup of OnStart, Run, and OnStop, but after authoring several windows services I got tired of writing the same code over and over again. Thus I created the WindowServiceTasks library. Now whenever I need to do another task in a service, I just implement the WindowsServiceTaskBase or WindowsServiceLoopBase class, and my code is all ready to go!

WindowsServiceTasks

Run multiple tasks in a single WindowsService, and let the base library do all of the work setup and tear down for you. The WindowsServiceTasks NuGet package is simple, flexible, and extremely light weight.

Example

public static class Program
{
    public static void Main(params string[] args)
    {
        var logger = new Logger("Demo.log");
        var emailTask = new EmailServiceTask(logger);
        var failTask = new FailServiceTask(logger);
 
        var service = new Service1(logger, emailTask, failTask);
        service.Start(args);
    }
}
public class EmailServiceTask : WindowsServiceLoopBase
{
    private readonly ILogger _logger;
 
    public EmailServiceTask(ILogger logger)
    {
        _logger = logger;
    }
 
    protected override int LoopMilliseconds
    {
        get { return 2000; }
    }
 
    protected override void HandleException(Exception exception)
    {
        _logger.Log(exception);
    }
 
    protected override void RunLoop()
    {
        // TODO Send Email!
        _logger.Log("EmailServiceTask.RunLoop - Sending an email");
    }
 
    public override void OnStart(string[] args)
    {
        _logger.Log("EmailServiceTask.OnStart");
    }
 
    public override void OnStop()
    {
        _logger.Log("EmailServiceTask.OnStop");
    }
 
    protected override void DisposeResources()
    {
    }
}
Shout it

Enjoy,
Tom

4 comments:

  1. Hey Tom, Tim Rayburn here, just browsing some of your older posts. If you haven't done so, you should check out TopShelf at topshelf-project.com, amazing project for making Services development awesome.

    ReplyDelete
  2. Hey Tim! You're not the first person to suggest that I take a look at TopShelf. My original excuse was minimalism , but now I'll have to go play with it!

    ReplyDelete
  3. while you are facing problem in essay writing, I will recommend you to visit www.bestessaywriting.org and ask them for services as per my recommendations this is the best platform that can provide you with excellent quality essays.

    ReplyDelete

Real Time Web Analytics