Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire timer_elapsed immediately from OnStart in windows service

I'm using a System.Timers.Timer and I've got code like the following in my OnStart method in a c# windows service.

timer = new Timer();
timer.Elapsed += timer_Elapsed;
timer.Enabled = true;
timer.Interval = 3600000;
timer.Start();

This causes the code in timer_Elapsed to be executed every hour starting from an hour after I start the service. Is there any way to get it to execute at the point at which I start the service and then every hour subsequently?

The method called by timer_Elapsed takes too long to run to call it directly from OnStart.

like image 945
Andy Avatar asked Apr 21 '11 10:04

Andy


1 Answers

If you want your Timer to be fired immediately then you could simply just initialize the Timer object without a specified interval (it will default to 100ms which is almost immediately :P), then set the interval within the called function to whatever you like. Here is an example of what I use in my Windows Service:

private static Timer _timer;

protected override void OnStart(string[] args)
{
    _timer = new Timer(); //This will set the default interval
    _timer.AutoReset = false;
    _timer.Elapsed = OnTimer;
    _timer.Start();
}

private void OnTimer(object sender, ElapsedEventArgs args)
{
    //Do some work here
    _timer.Stop();
    _timer.Interval = 3600000; //Set your new interval here
    _timer.Start();
}
like image 178
John Odom Avatar answered Oct 12 '22 15:10

John Odom