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.
Please check this answer in SO. It uses a ASP.NET timer control to raise events on specific time of the day. I suggest you keep this value as a config entry. Also there are other suggestions in that as well.
How to use the .NET Timer class to trigger an event at a specific time?
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 :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.