I have a windows service where in I want to create a file every 10 seconds.
I got many reviews that Timer in Windows service would be the best option.
How can I achieve this?
I have a windows service where in I want to create a file every 10 seconds.
I got many reviews that Timer in Windows service would be the best option.
How can I achieve this?
Firstly, pick the right kind of timer. You want either
System.Timers.Timer
orSystem.Threading.Timer
- don't use one associated with a UI framework (e.g.System.Windows.Forms.Timer
orDispatcherTimer
).Timers are generally simple
Elapsed
event (or pass it a callback on construction),and all will be well.
Samples:
I have a bit more information on this page, although I haven't updated that for a long time.
This should just be a case of firing up a
System.Timers.Timer
with the rightInterval
(andAutoReset
set to true), and handlingElapsed
(but watch out; the callback is not on any particular thread).MSDN has an example: http://msdn.microsoft.com/en-us/library/system.timers.timer.elapsed.aspx
also from MSDN:
I would not recommend
System.Timers.Timer
since it silently eats unhandled exceptions and therefore hides errors that you should fix. imho better that your code blows up in your face if you do not handle exceptions properly.As for
System.Threading.Timer
I tend to use theChange
method to start/stop the timer in a pattern like this:Here you have example how to use Timer in Windows Service.
fully tested solution...
This is how you do it simply
The Code above is the whole service with the timer. I realize this is an old post but it took me hours to figure this out. Hopefully it helps someone out there.