Skip to content

Instantly share code, notes, and snippets.

@jermdavis
Last active May 12, 2018 20:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jermdavis/23e1ca98e7faf37663aac26949b8ab2a to your computer and use it in GitHub Desktop.
Save jermdavis/23e1ca98e7faf37663aac26949b8ab2a to your computer and use it in GitHub Desktop.
Simple scheduler class
using System;
using System.Threading;
public class FunctionScheduler
{
private int _runEveryMs;
private Action _actionToRun;
private Timer _timer = null;
private object _lock = new object();
public FunctionScheduler(int runEveryMs, Action actionToRun)
{
_runEveryMs = runEveryMs;
_actionToRun = actionToRun;
}
public void Start()
{
_timer = new Timer(new TimerCallback(timerTick), null, 0, _runEveryMs);
}
public void Stop()
{
_timer.Dispose();
}
private void timerTick(object o)
{
if (Monitor.TryEnter(_lock))
{
try
{
_actionToRun?.Invoke();
}
finally
{
Monitor.Exit(_lock);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment