Skip to content

Instantly share code, notes, and snippets.

@alex-groshev
Created May 11, 2015 17:08
Show Gist options
  • Save alex-groshev/fbb61d65fd201a2ec8f7 to your computer and use it in GitHub Desktop.
Save alex-groshev/fbb61d65fd201a2ec8f7 to your computer and use it in GitHub Desktop.
Invoking multiple handlers periodically from Topshelf Windows Service (using System.Timers.Timer)
using System;
using System.Collections.Generic;
using System.Timers;
using Topshelf;
namespace ConsoleApplication
{
public interface IProcess
{
void ProcessHandler(object o, ElapsedEventArgs args);
}
public class Process1 : IProcess
{
public void ProcessHandler(object o, ElapsedEventArgs args)
{
Console.WriteLine("Process1");
}
}
public class Process2 : IProcess
{
public void ProcessHandler(object o, ElapsedEventArgs args)
{
Console.WriteLine("Process2");
}
}
public class ProcessRunner
{
public ProcessRunner(IEnumerable<IProcess> processes)
{
_timer = new Timer(100);
foreach (var process in processes)
{
_timer.Elapsed += process.ProcessHandler;
}
}
public void Start()
{
_timer.Start();
}
public void Stop()
{
_timer.Stop();
}
private readonly Timer _timer;
}
class Program
{
static void Main(string[] args)
{
HostFactory.Run(x =>
{
x.Service<ProcessRunner>(s =>
{
s.ConstructUsing(name => new ProcessRunner(
new List<IProcess>
{
new Process1(),
new Process2()
}));
s.WhenStarted(_ => _.Start());
s.WhenStopped(_ => _.Stop());
});
x.RunAsLocalSystem();
// other settings here...
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment