Johan
Johan

Reputation: 89

Make Cache object expire at midnight

I have the following code:

var tempList = new BrandCollection();
            if (HttpContext.Current.Cache["cachedDeviceList"] == null)
            {
                tempList = Provider.GetDeviceData(info);
                HttpContext.Current.Cache.Insert(...);
            }
            else
            {
                tempList = 
            }

Cache.Insert() method is overloaded where I can set the dependencies, sliding and absolute expiration. I want to make the Cache expire at midnight. How do I do that? Thank in advance!

Upvotes: 1

Views: 3410

Answers (1)

PhilPursglove
PhilPursglove

Reputation: 12589

Absolute expiration is the way to do this - it's shorthand for 'this expires at an absolute point in time' as opposed to 'in twenty minutes from now'. So when you put an item into the cache, you need to calculate when midnight will be and then use that as the expiration point e.g.

var tempList = new BrandCollection(); 
if (HttpContext.Current.Cache["cachedDeviceList"] == null) 
{ 
    tempList = Provider.GetDeviceData(info); 

    // Find out when midnight will be by taking Today and adding a day to it
    DateTime expirationTime = DateTime.Today.AddDays(1)
    HttpContext.Current.Cache.Insert("cachedDeviceList", tempList, null, expirationTime, NoSlidingExpiration, CacheItemPriority.Normal, null); 
} 
else 
{
    ...
}

Upvotes: 5

Related Questions