Created
May 11, 2015 17:08
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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