Sunday 15 June 2008

Watchdog timer

I had a need for a simple watchdog timer, to tick only when the time had elapsed, and also to be able to continuously restart it, to stop the timer from ticking.

This was an excuse to use some inheritance, as I took a standard System.Timers.Timer and subclassed it to create my own WatchdogTimer.

The code for this is below:

   1:  using System;
   2:  using System.Timers;
   3:   
   4:  namespace MyNamespace
   5:  {
   6:      public class WatchdogTimer : Timer
   7:      {
   8:          private double _timeout;
   9:   
  10:          public WatchdogTimer()
  11:            : base()
  12:          {
  13:          }
  14:   
  15:          public WatchdogTimer(double interval)
  16:            : base(interval)
  17:          {
  18:              this._timeout = interval;
  19:          }
  20:   
  21:          // Reset and restart the timer.
  22:          public void Restart()
  23:          {
  24:              // Resetting the interval property
  25:              // forces the timer to restart.
  26:              this.Interval = this._timeout;
  27:          }
  28:      }
  29:  }


It works once the timer has been started by conventional means (i.e. timer.Start();), then it is simply a matter of calling restart every time you need to. In my case it was because I am performing some serial or TCP communications functions, and needed a timeout should they fail.

Each time I sent a comms response, I expected to receive a response within an allotted period of time. If the response was received, then I called Restart() on the WatchdogTimer. If the response is not received, then the timer will timeout and 'Tick', allowing any code necessary to handle failed comms to run.

0 comments: