A Windows Service without a template
Written by Harry Fairhead   
Friday, 14 August 2009
Article Index
A Windows Service without a template
A simple service
Using Timers
Event log service
Other logs

Using timers

In most cases a service creates an object or method that does the desired task when it is started and similarly destroys that object when stopped.

The big problem in building any service is to get the object to do something when action is needed. There are two general approaches:

  • You can try and handle an appropriate event that signals that there is work for the service to do. For example, you can use the FileSystemWatcher to make the service respond to a change to the filing system.

or

  • You can implement a timer and wake the service up to do something at regular intervals.

The timer approach is so common that it is worth seeing how it is implemented and the final example shows how to work with an event.

First we need a timer object; add:

using System.Threading;

to the start of the program.

Unfortunately there are two timer classes, one in Windows.Forms and one in Threading. To make it clear which we want to use we need to use a fully qualified name when we declare a variable:

private System.Threading.Timer timer;

Now we can create the timer object and set it ticking when the service is started:

protected override void OnStart(
string[] args)
{
TimerCallback tick=
new TimerCallback(SayHello);
timer = new System.Threading.Timer(
tick, null, 0, 10000);
}

and remember to destroy the timer object when the service is stopped:

protected override void OnStop()
{
timer.Dispose();
}

The only missing piece is the method used to create the TimerCallback delegate and this simply makes use of the message box call described earlier:

 

private void SayHello(object state)
{
MessageBox.Show("Hello Service",
"SimpleService",
MessageBoxButtons.OK,
MessageBoxIcon.Information,
MessageBoxDefaultButton.Button1,
MessageBoxOptions.ServiceNotification);
}

If you start the service a message box will pop up every 10 seconds until you stop the service. Stop the service to stop the messages!

<ASIN:1861007728>

<ASIN:0735625301>
<ASIN:0321374460>



Last Updated ( Friday, 14 August 2009 )