Skip to content

Instantly share code, notes, and snippets.

@trcio
Last active August 29, 2015 14:02
Show Gist options
  • Save trcio/777ca6920a0a61792100 to your computer and use it in GitHub Desktop.
Save trcio/777ca6920a0a61792100 to your computer and use it in GitHub Desktop.
An Interval Timer for C#. Specify the minimum and maximum time between intervals, and let the timer do the rest!
using System;
using System.Threading;
public sealed class IntervalTimer
{
private Timer timer;
private Random rand;
private int min, max;
public event Action Interval;
public IntervalTimer()
{
timer = new Timer(Callback, null, -1, -1);
rand = new Random();
}
private void Callback(object state)
{
try
{
Interval();
}
finally
{
timer.Change(rand.Next(min, max), Timeout.Infinite);
}
}
/// <summary>
/// Sets the interval of the timer in milliseconds.
/// </summary>
/// <param name="min">Minimum amount of time between intervals.</param>
/// <param name="max">Maximum amount of time between intervals.</param>
public void SetInterval(int min, int max)
{
this.min = min;
this.max = max;
}
/// <summary>
/// Starts the timer.
/// </summary>
public void Start()
{
timer.Change(min, Timeout.Infinite);
}
/// <summary>
/// Stops the timer.
/// </summary>
public void Stop()
{
timer.Change(-1, -1);
}
/// <summary>
/// Disposes the internal timer.
/// </summary>
public void Dispose()
{
timer.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment