Created
June 6, 2013 23:05
-
-
Save damieng/5725720 to your computer and use it in GitHub Desktop.
Simple pattern for background ASP.NET tasks. Just BackgroundService.Start(SomeMethod, TimeSpan.SomeInterval). Based on Phil Haack's sample.
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