Last active
August 4, 2024 02:37
-
-
Save jermdavis/23e1ca98e7faf37663aac26949b8ab2a to your computer and use it in GitHub Desktop.
Simple scheduler class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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