Home > C#

Timer Not Working in Windows Service

20. March 2009

So I had the same problem as all the others out there with a timer not working correctly in a Windows Service.  Here was my situation.  I was using the System.Threading.Timer and had a callback assigned to it.  Everything would work fine, but for some reason after 10-14 hours it stopped running.  At first I thought it was my code in the service so I added logging code and try-catches to a lot of places to see where it may be failing.  I also added code in the callback event just to make sure it was hitting that, well it wasn't.  It never made it to the callback event, hence why nothing else was getting logged. 

So I got some advice from my friend Quintin (check him out on stackoverflow) and he suggested using System.Timers.Timer.  And sure enough it worked! Now, I'm personally still puzzled as to why this works because alot of articles on the net said don't use System.Timers.Timer in a windows service and use System.Threading.Timer instead (hence why I chose that one first).  Anyway, here is an article on MSDN that explains the difference of the timers and just the small code snippet of my timer in the service.

http://msdn.microsoft.com/en-us/library/tb9yt5e6(VS.80).aspx

This logic is called via the OnStart method for the service

System.Timers.Timer _timer = new System.Timers.Timer();
_timer.Enabled = true;
_timer.Interval = 1800000;

_timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);

Good luck

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

C#

blog comments powered by Disqus