A few months ago, I came across an interesting technique in ASP.NET to simulate background processes @
http://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/. I have tried this approach in a couple of my projects and it works. I would like to extend the post at this link with my experiences after implementing this technique in a real-time project.
Firstly, thanks to whoever came up with this interesting idea. It works for sure but with limitations.
Let me just copy and paste the code snippet from the above url for reference purposes:
private static CacheItemRemovedCallback OnCacheRemove = null;
protected void Application_Start(object sender, EventArgs e)
{
AddTask("DoStuff", 60);
}
private void AddTask(string name, int seconds)
{
OnCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved);
HttpRuntime.Cache.Insert(name, seconds, null,
DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration,
CacheItemPriority.NotRemovable, OnCacheRemove);
}
public void CacheItemRemoved(string k, object v, CacheItemRemovedReason r)
{
// do stuff here if it matches our taskname, like WebRequest
// re-add our task so it recurs
AddTask(k, Convert.ToInt32(v));
}
- We can have only one background process per web application (ref : CacheItemRemoved). If you have a requirement to perform two tasks at different intervals of time (say one at every 10 mins and the other at every one hour), then the approach that I propose is to have the background process wake up at regular intervals of time (say 10 sec) and track the timestamp when a particular process executed recently. This is more of an implementation level logic and I hope you got the idea :-)
- As a good coding practice, one would avoid inline business logic (in the CacheItemRemoved) but cache a business object and invoke a method on the business object at regular intervals (in the CacheItemRemoved method). Beware that you might run into a situation where your business object got garbage collected (eg: the process that runs every one hour in my example above) and your background process ends up doing nothing !! To solve this problem, I propose to create a blank file on the file system (preferably in the root directory of your web app) and the existance of this blank file indicates that the background process should be kept alive. So if you perform a null check on the cached business object and you find that it is "null", just instantiate and re-insert the new object in cache so that your background process works as expected :-)
The fundamental approach is awesome and I hope my experiences help developers solve a couple of practical problems with the approach :-)
Cheers.