0

I have a window service and i'm using System.Timers.Timer to schedule my service

protected override void OnStart(string[] args)
{
    timer_= new System.Timers.Timer(intervalTime * 1000);
    timer_.Elapsed += new System.Timers.ElapsedEventHandler(TimerEvent);
    timer_.Enabled = true;
}


private void TimerEvent(object sender, System.Timers.ElapsedEventArgs e)
{
    DoSth();
}

I find that, the Dosth() function doesn't run exactly when i start the service, but after intervalTimer seconds.I want it to run exactly after i start the service, so i call the function Dosth() before statment timer_.Enabled = true;. But i got another problem that. the distance of the 1st and the 2nd process is not exactly equal intervalTime, but base on processing time of DoSth() function. How can i solve this?

  • How about you call `Dosth()` after `timer_.Enabled = true;` – artm Oct 28 '14 at 10:02
  • 1
    To answer your first question just call `DoSth();` in the `OnStart` event before wiring up the timer. If you just want a program to run at set times then have you thought about moving to a console application and scheduling execution with windows task scheduler? – Ben Robinson Oct 28 '14 at 10:02
  • The trick to equal intervals is to get a [time stamp at the start of the callback](http://stackoverflow.com/a/12797382/314291), and then to measure the time in the callback and subtract this from the next tick interval. Also, do one interval at a time (`Timeout.Infinite`) to prevent reentrancy issues. – StuartLC Oct 28 '14 at 10:02
  • @artm: It still not work :( – Nguyen Ba Tu Oct 28 '14 at 10:11
  • Take a look at Quartz.net, makes the above very easy. Also have a look at Topshelf too, it makes writing services much more simple. – Jack Hughes Oct 28 '14 at 10:15

0 Answers0