I am trying to use a timer in a windows service. The service is able to start and stop and I write something to the event log when this happens, this works. My problem is that I also want to use a timer that keeps running and write something to event log every time the timeElapsed event is fired.
EDIT: (I changed the code, so the timer is a field, but still not the result I would expect, no log entries in event log)
using System.Timers;
initializing the service:
public Timer timer;
public MonitorService()
{
InitializeComponent();
timer = new Timer(10000);
//Some code that really doesn't matter
}
The on start event
protected override void OnStart(string[] args)
{
// Hook up the Elapsed event for the timer.
timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
timer.Enabled = true;
timer.Start();
EventLogger.WriteEntry("Biztalk monitoring service started", EventLogEntryType.SuccessAudit);
// If the timer is declared in a long-running method, use
// KeepAlive to prevent garbage collection from occurring
// before the method ends.
// GC.KeepAlive(timer);
}
private int count =0;
The on timed event: (This is what won't work, there are no entries written to event log every 10 seconds, while I expect it to do)
// Specify what you want to happen when the Elapsed event is
// raised.
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
//Some other code that doesn't mather
count++;
EventLogger.WriteEntry(string.Format("TimerEvent has ran {0} times. Total time is: {1}", count, e.SignalTime), EventLogEntryType.Information);
}
The on stop event:
protected override void OnStop()
{
EventLogger.WriteEntry("Biztalk monitoring service stopped", EventLogEntryType.Warning);
}
Main
For those who wonder this is my main method in Program.cs:
///<summary>
///The main entry point for the application.
///</summary>
static void Main()
{
var servicesToRun = new ServiceBase[]
{
new MonitorService()
};
ServiceBase.Run(servicesToRun);
}
Already asked? Yes indeed!
I am aware of the fact that this question has been asked earlier like here: Windows service with timer AND Best Timer for using in a Windows service
But those solutions doesn't seem to solve my problem.
Any suggestions are welcome!