Skip to content

Instantly share code, notes, and snippets.

@AndyConlisk
Created January 3, 2015 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndyConlisk/eb24d5694af818175770 to your computer and use it in GitHub Desktop.
Save AndyConlisk/eb24d5694af818175770 to your computer and use it in GitHub Desktop.
Simple Background Tasks for ASP.NET
//Easy Background tasks in ASP.NET projects
//Inspiration from http://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/
//This code is added into the Global.asax file. In the Application_Start() method
private static CacheItemRemovedCallback OnCacheRemove = null;
protected void Application_start()
{
//The register code that is put in here
//Here is where you add all the tasks you want to start on application start
AddTask("taskA", 60); //This will add and setup taskA to run every 60 seconds
AddTask("taskB", 60 * 5); //This will add and setup taskB to run every 5 min
}
private AddTask(string taskName, int seconds)
{
OnCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved);
HttpRuntime.Cache.Insert(taskName, seconds, null, DateTime.Now.AddSeconds(seconds),
Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, OnCacheRemove);
}
private void CacheItemRemoved(string task, object obj, CacheItemRemovedReason reason)
{
switch(task)
{
case "taskA":
//Call function to handle taskA stuff
break;
case "taskB":
//Call fucntion to handle taskB stuff
}
AddTask(task, Convert.ToInt32(obj)) //readds the task to get run again in the set time
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment