如何在每天的特定时间删除缓存项目



我希望缓存元素中的项目每天在特定时间删除一次,比如晚上11:59:59。
我知道缓存中有一个属性absoluteExpiration,可以在一定的时间段内使用
我使用以下代码在缓存中设置值

   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;
    } 

但是我如何设置缓存到期的确切时间
我需要manipulate时间变量并计算time difference并设置absoluteExpiration吗?或者还有其他方法。

请在SO中检查此答案。它使用ASP.NET计时器控件在一天中的特定时间引发事件。我建议您将此值保留为配置条目。此外,还有其他建议。

如何使用.NET Timer类在特定时间触发事件?

我发现创建函数的方法如下

    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);
    }

这给了我一个双倍的值,我在函数中使用了这个值,如下

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;
} 

完成:)

最新更新