Sunday, August 23, 2009

Timer for Windows Service

Windows Services can only use System.Timers.Timer class, not the System.Windows.Forms.Timer control. So make sure you are using the correct class.

There are five members/events/methods in Timer that you care about:
.Elapsed - this is an event that fires every specified interval of time. You need to wire it up to a event handler like this:
testTimer.Elapsed += new ElapsedEventHandler(testTimer_Elapsed);

then create the testTimer_Elapsed function like this:

private void testTimer_Elapsed(object sender, ElapsedEventArgs e)
{
//do stuff
}

.Interval - this is how often you want the Elapsed event to fire and it's in milliseconds. To make things easier you may want to create some functions that convert milliseconds to more useful time periods, like seconds.
1 second = 1000 milliseconds
1 minute = 60 seconds
so 1 minute = 60 * 1000
etc...

.Enabled - set this true if you want the Timer to work. Make it false when the timer isn't needed.

.Start()- Call this to make the Timer start counting down.
.Stop() - Call this when you no longer want the Timer to count down

Full Example:
using System.Timers;

namespace TestingTimer
{
public partial class MyNewService : ServiceBase
{
int count = 0;
public MyNewService()
{
InitializeComponent();

}

protected override void OnStart(string[] args)
{
Timer testTimer = new Timer();
testTimer.Elapsed += new ElapsedEventHandler(testTimer_Elapsed);
testTimer.Interval = getMS(10);
testTimer.Enabled = true;
testTimer.Start();


}
private int getMS(int Seconds)
{
return Seconds * 1000;
}

protected override void OnStop()
{
}

private void testTimer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
System.Windows.Forms.MessageBox.Show("Event #" + (++count).ToString());
}
catch (Exception a)
{
EventLog.WriteEntry(a.ToString());
}
}
}
}

References:
1. http://www.codeguru.com/columns/dotnet/article.php/c6919
2. http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx

No comments:

Post a Comment

There was an error in this gadget