Search code examples
c#windows-servicestimer

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.


Solution

  • Just start a threadpool thread to call the worker function, just like Timer does. Like this:

            timer.Elapsed += timer_Elapsed;
            ThreadPool.QueueUserWorkItem((_) => DoWork());
        ...
    
        void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
            DoWork();
        }
    
        void DoWork() {
            // etc...
        }