Created
March 23, 2018 13:06
-
-
Save TwitchBronBron/1da9b97498954d533bb5ee3c6bcccf23 to your computer and use it in GitHub Desktop.
A simple timer for .net
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.Collections.Generic; | |
using System.Threading; | |
using System.Threading.Tasks; | |
public class Timer | |
{ | |
public static List<Action> Callbacks = new List<Action>(); | |
private static bool IsRunning = false; | |
public static void Register(Action callback) | |
{ | |
Callbacks.Add(callback); | |
Timer.EnsureRunning(); | |
} | |
private static Task RunTask; | |
private static Task EnsureRunning() | |
{ | |
lock (Callbacks) | |
{ | |
if (Timer.IsRunning == false) | |
{ | |
Timer.IsRunning = true; | |
try | |
{ | |
RunTask = Timer.Run(); | |
} | |
catch (Exception) | |
{ | |
//eat the exception so we don't bring the process down | |
} | |
} | |
} | |
return RunTask; | |
} | |
/// <summary> | |
/// Runs at one second past the minute, every minute. | |
/// </summary> | |
private static async Task Run() | |
{ | |
//wait until the next whole minute | |
var secondsToPause = 60 - DateTime.UtcNow.Second; | |
if (secondsToPause > 0) | |
{ | |
await Task.Delay((secondsToPause + 1) * 1000); | |
} | |
while (true) | |
{ | |
//launch new threads for each action | |
foreach (var callback in Timer.Callbacks) | |
{ | |
var thread = new Thread(() => | |
{ | |
try | |
{ | |
callback(); | |
} | |
catch (Exception) | |
{ | |
//eat the exception. Nothing we can do about it, we don't want to bring the process down | |
} | |
}); | |
thread.Start(); | |
} | |
//sleep until the next whole minute | |
//wait until the next whole minute | |
var nextWholeMinuteSeconds = 60 - DateTime.UtcNow.Second; | |
//ensure we pause until the next second | |
nextWholeMinuteSeconds = nextWholeMinuteSeconds != 0 ? nextWholeMinuteSeconds : 60; | |
await Task.Delay((nextWholeMinuteSeconds + 1) * 1000); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment