I want that the items in the cached element should be deleted once daily at a particular time say at 11:59:59 pm.
I know that there is a property absoluteExpiration
in cache which can be use for certain time period.
I am using the following code to set values in cache
public static Collection<CProductMakesProps> GetCachedSmartPhoneMake(HttpContext context)
{
var allMake = context.Cache["SmartPhoneMake"] as Collection<CProductMakesProps>;
if (allMake == null)
{
allMake = new CModelRestrictionLogic().GetTopMakes();
context.Cache.Insert("SmartPhoneMake", allMake, null,
DateTime.Now.AddHours(Int32.Parse(ConfigurationManager.AppSettings["MakeCacheTime"])),
Cache.NoSlidingExpiration);
}
return allMake;
}
But how I can set the exact time when cache should expire.
Do I need to manipulate
the time variable and calculate the time difference
and set the absoluteExpiration
or there is some other way.
I found the way I have created a function as below
private static double GetTimeLeft()
{
//create a time stamp for tomorow 00:10 hours
var tomorrow0010Minute = DateTime.Now.AddDays(1).Date.AddMinutes(10);
return Math.Round((tomorrow0010Minute - DateTime.Now).TotalHours);
}
This gives me a double value which I used in my function as follow
public static Collection<CProductMakesProps> GetCachedSmartPhoneMake(HttpContext context)
{
var allMake = context.Cache["SmartPhoneMake"] as Collection<CProductMakesProps>;
if (allMake == null)
{
allMake = new CModelRestrictionLogic().GetTopMakes();
context.Cache.Insert("SmartPhoneMake", allMake, null,
DateTime.Now.AddHours(GetTimeLeft()),
Cache.NoSlidingExpiration);
}
return allMake;
}
And done :)