An easy to use timer that runs in the background and provides useful functions like callbacks and states. For ideas, feedback or anything else just open an issue.
🟡 Project status: Maintenance mode[?]
| Package | NuGet |
|---|---|
| BlyZe.BackgroundTimer |
Initialize a new BackgroundTimer instance.
var timer = new BackgroundTimer();
static void BackgroundTimerCallback(int tick) => Console.WriteLine("Current tick: " + tick); //tick is the current tick of the running timer
timer.Start(TimeSpan.FromMilliseconds(69), BackgroundTimerCallback); //Starts a timer that executes the callback method every 69 milliseconds
timer.Stop(); //Stops the timer
await timer.StopAsync(); //Stops the timer asynchronously
await timer.StopAsync(TimeSpan.FromSeconds(5)); //Stops the timer asynchronously after 5 seconds
int currentTick = timer.CurrentTick; //Get the current tick the timer is on
BackgroundTimerState currentState = timer.State; //Get the current timer state
TimeSpan timerPeriod = timer.Period; //Get the period the timer is running on
You can only run one timer with one instance. If you want to run multiple timers simultaneously you have to create multiple timer instances.
var timer = new BackgroundTimer();
timer.Start(TimeSpan.FromMilliseconds(69), BackgroundTimerCallback, TimeSpan.FromSeconds(1.5));
timer.Start(TimeSpan.FromMilliseconds(420), BackgroundTimerCallback); //That timer will not run
var timer = new BackgroundTimer();
timer.Start(TimeSpan.FromMilliseconds(69), BackgroundTimerCallback, TimeSpan.FromSeconds(1.5)); //Starts the timer
await Task.Delay(2500); //Imitates timer running
//NOTE: You have to use the StopAsync(); method or a while loop to wait for the timer to stop otherwise the timer.Start(); executes before the timer actually stopped!
//First variant - async
if (timer.State is not BackgroundTimerState.NotRunning) await timer.StopAsync();
timer.Start(TimeSpan.FromMilliseconds(420), BackgroundTimerCallback); //Start new timer safely
//Second variant - loop
if (timer.State is not BackgroundTimerState.NotRunning) timer.Stop();
while (timer.State is not BackgroundTimerState.NotRunning) { }
timer.Start(TimeSpan.FromMilliseconds(420), BackgroundTimerCallback); //Start new timer safely