Created
January 3, 2015 22:11
-
-
Save AndyConlisk/eb24d5694af818175770 to your computer and use it in GitHub Desktop.
Simple Background Tasks for ASP.NET
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
//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