Created
May 18, 2015 11:52
-
-
Save alex-groshev/545826470ed4f174dfd8 to your computer and use it in GitHub Desktop.
Invoking multiple handlers periodically from Topshelf Windows Service (using System.Threading.Timer) using Reflection
This file contains 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.Threading; | |
using Topshelf; | |
namespace ConsoleApplication | |
{ | |
public interface IProcess | |
{ | |
void Perform(); | |
} | |
public class Process1 : IProcess | |
{ | |
public void Perform() | |
{ | |
Console.WriteLine("Process1"); | |
} | |
} | |
public class Process2 : IProcess | |
{ | |
public void Perform() | |
{ | |
Console.WriteLine("Process2"); | |
} | |
} | |
public class ProcessRunner | |
{ | |
public ProcessRunner(IEnumerable<string> typeNames, CancellationToken ct) | |
{ | |
foreach (var typeName in typeNames) | |
{ | |
var type = Type.GetType(typeName); | |
if (type != null) | |
{ | |
var process = Activator.CreateInstance(type) as IProcess; | |
if (process != null) | |
{ | |
_processes.Add(process); | |
} | |
} | |
} | |
_cts = CancellationTokenSource.CreateLinkedTokenSource(ct); | |
} | |
public void Start() | |
{ | |
_timer = new Timer((x => | |
{ | |
foreach (var process in _processes) | |
{ | |
process.Perform(); | |
} | |
_timer.Change(1000, Timeout.Infinite); | |
}), null, 0, Timeout.Infinite); | |
_cts.Token.Register(_timer.Dispose); | |
} | |
public void Stop() | |
{ | |
_cts.Cancel(); | |
} | |
private Timer _timer; | |
private readonly CancellationTokenSource _cts; | |
private readonly List<IProcess> _processes = new List<IProcess>(); | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var cts = new CancellationTokenSource(); | |
var token = cts.Token; | |
HostFactory.Run(x => | |
{ | |
x.Service<ProcessRunner>(s => | |
{ | |
s.ConstructUsing(name => new ProcessRunner(new List<string> | |
{ | |
"ConsoleApplication.Process1", | |
"ConsoleApplication.Process2" | |
}, token)); | |
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