
Cache.Insert(String, Object, CacheDependency, DateTime, TimeSpan, CacheItemUpdateCallback)
http://msdn.microsoft.com/en-us/library/cc491414.aspxMy new favorite method in .Net cache'ing. Before I explain why I love it I'm going to show you how it works in a very easy way, because that's all you really care about anyways....I know this because I'm the exact same way annnnnnd Google Analytics tells me so by your actions visitors.
The place I like to put this method is in my constructor on my data layer, this way it's called with frequency.
public static class DataLayer
{
static DataLayer()
{
HttpContext.Current.Cache.Insert("AnyStringYouLike",
"AnyStringYouLike",
null,
DateTime.Now.AddMinutes(5),
System.Web.Caching.Cache.NoSlidingExpiration,
new CacheItemUpdateCallback(FunctionYouWantToCall));
}
public static void FunctionYouWantToCall(string aKey,
CacheItemUpdateReason aReason,
out object anObject,
out CacheDependency dependency,
out DateTime expiration,
out TimeSpan aTimeSpan)
{
if (DateTime.Now.Day == 22)
{
if (AFeedIMade.GenerateFeed())
{
ErrorHelper.LogError("AFeedIMade", "Success");
}
else
{
ErrorHelper.LogError("AFeedIMade", "Failure");
}
}
dependency = null;
expiration = DateTime.Now.AddMinutes(20);
aTimeSpan = Cache.NoSlidingExpiration;
anObject = "AnyStringYouLike";
}
}
What's happening here?
- I insert into cache a delegate that runs a function I specify I would like to run at a specific time. I do this by saying check the cache initially every five minutes, but once it jumps into the function every 20.
- Once it's in the function if the day is the 22nd of the month then I run the code to generate my feed, if it's not then I simply set the cache to check it every 20 minutes.
The first question you may ask your self is why don't you set the cache to check the time every 22 days or so. The problem with that is what if you set it back 22 days on the 21st day. Then you miss the day you want to check, the 22nd for that month, and your feed (or whatever you are having the method do) gets delayed by at least one month. Since every month is different in length, it's just not a smart decision. For good measure I've found that having the cache checked every x minutes under 60 minutes is the best way to go. It's less likely for a specified time frame to be missed in the function.
Last note, if by chance you are calling the cache outside of the websites context don't forget you can use:
HttpContext.CurrentLike so:
HttpContext.Current.Cache.Insert(String, Object, CacheDependency, DateTime, TimeSpan, CacheItemUpdateCallback)