Monday, April 6, 2015

An Interval Timer Class - Performing a task at regular intervals

Sometimes you need to do certain tasks at regular intervals such as logging or publishing metrics. Instead of littering your code with repeated checks whether desired time has passed, we can encapsulate this logic in a simple class IntervalTimer.

Helper Class

public class IntervalTimer
{
DateTime _lastCheckpoint;
TimeSpan _tripInterval;

public IntervalTimer(TimeSpan tripInterval)
{
_lastCheckpoint = DateTime.UtcNow;
_tripInterval = tripInterval;
}

public bool IsTripped
{
get
{
return DateTime.UtcNow > 
              _lastCheckpoint.Add(_tripInterval);
}
}

public void Reset()
{
_lastCheckpoint = DateTime.UtcNow;
}
}

Usage

// initialize a timer that trips every minute
var intervalTimer = new IntervalTimer(TimeSpan.FromMinutes(1));

// this code should probably be run on a separate thread
//   especially for a GUI application
while(true)
{
if (intervalTimer.IsTripped)
{
// Do your thing here (log, publish metrics, etc.)

intervalTimer.Reset();
}
Thread.Sleep(1000);
}