Question

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.

Was it helpful?

Solution 2

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 :)

OTHER TIPS

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top