System.threading.timer does not work in Windows Service

I am using System.threading.timer in a windows service. But the timer did not complete successfully. Below is the code.

protected override void OnStart(string[] args) { try { eventLog1.WriteEntry("In OnStart"); TimeSpan dueMinutes = TimeSpan.FromMinutes(1); TimeSpan fromMinutes = TimeSpan.FromMinutes(1); System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(CallBack), null, dueMinutes, fromMinutes); /* System.Timers.Timer timer = new System.Timers.Timer(5 * 60 * 1000); timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); DBSyncHandler sync = new DBSyncHandler(); sync.startSync(); */ } catch (Exception ex) { if (!System.Diagnostics.EventLog.SourceExists("MySource")) { System.Diagnostics.EventLog.CreateEventSource("MySource", "MyEventLog"); } eventLog1.Source = "MySource"; eventLog1.Log = "MyEventLog"; eventLog1.WriteEntry("Error : " + ex.Message); } } public static void CallBack(object sender) { try { DBSyncHandler sync = new DBSyncHandler(); sync.startSync(); } catch (Exception ex) { EventLog eventLog1 = new EventLog(); if (!System.Diagnostics.EventLog.SourceExists("MySource")) { System.Diagnostics.EventLog.CreateEventSource("MySource", "MyEventLog"); } eventLog1.Source = "MySource"; eventLog1.Log = "MyEventLog"; eventLog1.WriteEntry("Error : " + ex.Message); } } 

After a successful installation. My workstation is restarting. When the machine restarts, the service is successful. But as soon as the service is called for the first time, it is not repeated for the next time, i.e. the service is not called again.

+4
source share
2 answers

Read the notes on MSDN: http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx

As long as you use the timer, you must keep a link to it. In the view with any managed object, the Timer is garbage collected when there are no links to it. The fact that the timer is still active does not prevent it from gathering.

System.Threading.Timer is a simple, lightweight timer that uses callback methods and is served by thread pool threads. This is not recommended for use with Windows Forms because its callbacks do not occur in the user interface thread. System.Windows.Forms.Timer is the best choice for use with Windows Forms. For server-side timer functionality, you can use System.Timers.Timer, which raises events and has additional features.

I think your timer object created in OnStart is being collected or deleted by gc. it should not be a local variable in this method, since it exhausts the scope.

+13
source

Your timer variable must be at class level. Once it goes out of scope, it will no longer work.

Microsoft's recommendation is to use System.Timers.Timer in server code.

Additional information is available on the MSDN website. http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx

+2
source

All Articles