Skip to content

Instantly share code, notes, and snippets.

@damieng
Created June 6, 2013 23:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save damieng/5725720 to your computer and use it in GitHub Desktop.
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.
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