-
-
Save mahizsas/07c3d4a549b270fd8b5a to your computer and use it in GitHub Desktop.
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
public class BackgroundService : IRegisteredObject | |
{ | |
public static void Start(Action action, TimeSpan interval) | |
{ | |
var backgroundService = new BackgroundService(interval, action); | |
HostingEnvironment.RegisterObject(backgroundService); | |
} | |
private Timer timer; | |
private BackgroundService(TimeSpan interval, Action work) | |
{ | |
timer = new Timer(s => work(), null, TimeSpan.Zero, interval); | |
} | |
public void Stop(bool immediate) | |
{ | |
var safeTimer = timer; | |
if (safeTimer != null) | |
{ | |
safeTimer.Dispose(); | |
timer = null; | |
} | |
if (immediate) | |
HostingEnvironment.UnregisterObject(this); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment