Easy Background Tasks in ASP.NET
As I work on the badge implementation for Stack Overflow, I needed a way to call the code that detects and awards the badges out of band. Traditionally this is done by something like cron
or scheduled tasks. I’d rather have the code stay inside our current codebase, though.
I asked on Twitter and got some good responses, everything from “write a service” to “use threads”. I also got a link to Simulate a Windows Service using ASP.NET to run scheduled jobs. Now this is interesting — it’s just simple enough to work:
-
At startup, add an item to the
HttpRuntime.Cache
with a fixed expiration. -
When cache item expires, do your work, such as
WebRequest
or what have you. - Re-add the item to the cache with a fixed expiration.
The code is quite simple, really:
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));
}
Works well in my testing; badges are awarded every 60 seconds like clockwork for all users.
3 Comments
Wow, this is very simple. So it works great you say? Any tips?
This is quite old (2008). Is this still relevant today? More precisely: have newer releases of ASP.NET added something better than this hack?
There is now a better mechanism with .Net Core hosted services https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-5.0&tabs=visual-studio