Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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