Wednesday, 11 March 2009

Adding timers in Windows Services

So if you have tried to add a standard windows timer (System.Windows.Forms.Timer)... you may notice the timer never gets executed. I think this is a poor design flaw made by Microsoft as timers are quite a fundamental part of services in the way they are architectured and constructed.

In any case, there is a workaround, we can use Threading Timers (System.Threading.Timer). These work in a similar fashion.

1. Instantiate a new System.Threading.Timer object

Timer newTimer1 = new Timer(new TimerCallback(newTimer1_Tick), null, 0, 5000);

- This requires a TimerCallback, so we will need a method called "newTimer1_Tick".
- null -> not required
- 0 -> this starts the timer immediatly (0 milliseconds)
- 5000 -> this is the interval... triggers every 5 seconds (5000 milliseconds)

2. Create the callback method...

private void newTimer1_Tick(object state)

- your timer logic falls within this method

3. Remember to dispose of the timers after use...


No comments: