I am using System.threading.timer in Windows Service.
But the timer is not successfully executed.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 successfull installation .My workstation is restarted.On restarting the machine ,the service is called successfully.But once the service is called first time ,it is not repeating for next time duration i.e. the service is not called again.
Read the notes on MSDN: http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx
I think that your timer object created in the OnStart is gc collected or disposed. it should not be a local variable in that method as it runs out of scope.