I’m writing a windows service to execute some method every x minutes, but I want the method to execute synchronously relative to the timer itself. The windows service have a Timer object (System.Timers.Timer) which starts and calls some method ‘DoWork’ every x minutes, but the timer must ‘stop’ while ‘DoWork’ is executing and starts again after the method is finished.
I’m aware that using the System.Windows.Forms.Timer class would give me the behavior I want, but I don’t want to add a System.Windows.Forms dll reference to my Service project.
Here is an example of ‘working’ code:
private System.Timers.Timer timer1;
public void MainMethod()
{
timer1 = new System.Timers.Timer();
timer1.Interval = 1000;
timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
timer1.Start();
}
void timer1_Elapsed(object sender, ElapsedEventArgs e)
{
timer1.Stop();
DoWork();
timer1.Start();
}
private void DoWork()
{
Thread.Sleep(2000);
Console.WriteLine("found!");
}
Running above in a console application (as a mockup before writing the windows service), the expected behavior should be for the console to write ‘found!’ every 3 seconds.
Just a side-note: I’m just using ‘Thread.Sleep(2000)’ to mimic a delay but it won’t form part of the actual code base.
Is there any other / “better” way to achieve this than my way above?
Thanks for reading my question and any input would be greatly appreciated.
You can’t use
System.Forms.Timerin a windows service because that would require a message pump and Windows services are not given a message pump stack that can be very large (plus you’d have to callApplication.Runto start one).The way you have it now is the way I implement periodic events. I’d add something to monitor whether your events take longer than the period; but other than that…