2

I am using cache.insert() method to add some data to cache, and it uses absolute expiration and expires once in 4 hours. Now I have a new requirement to expire the cache in specific times: 7am, 11am, 3pm, 7pm.

Is there a way to do it?

Current code:

ctx.Cache.Insert("stmodel", stModel, null,
                 DateTime.Now.AddHours(4), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, OnCachedItemRemoved);

Thanks in advance.

Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60
user1165815
  • 305
  • 2
  • 6
  • 21
  • I think you are looking for [Rounding DateTime objects](http://stackoverflow.com/questions/1393696/rounding-datetime-objects) – Alexei Levenkov Feb 20 '14 at 18:31
  • How does rounding Datetime will help in this requirement? – user1165815 Feb 20 '14 at 18:32
  • Isn't your question "how to find next moment in time rounded up to 4hours"? (also simple `if` with 4 conditions may be enough and more readable than rounding suggested in that post `DateTime.Now.AddHours(4) < DateTime.Today.AddHours(7) ? DateTime.Today.AddHours(7) : ...` ) – Alexei Levenkov Feb 20 '14 at 18:43
  • Just replace the DateTime.Now.AddHours with a method that returns the specific time. For example, you can call it GetNewExpiryTime. If it's greater than 7am and less then 11am, return today at 11am, etc, etc. – u84six Feb 20 '14 at 18:58

1 Answers1

3
ctx.Cache.Insert("stmodel", stModel, null,
             MyClass.getSpecificDateTime(), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, OnCachedItemRemoved);

 public static DateTime getSpecificDateTime()
    {
        TimeSpan currentTime = DateTime.Now.TimeOfDay;
        DateTime newTime = DateTime.Now;

        if (currentTime.Hours < 7){
            newTime = newTime.Date + new TimeSpan(7, 0, 0);
        }else if (currentTime.Hours < 11){
            newTime = newTime.Date + new TimeSpan(11, 0, 0);
        }else if (currentTime.Hours < 15) {
            newTime = newTime.Date + new TimeSpan(15, 0, 0);
        }else if (currentTime.Hours < 19){
            newTime = newTime.Date + new TimeSpan(19, 0, 0);
        }else {
            newTime = DateTime.Now.AddDays(1);
            newTime = newTime.Date + new TimeSpan(7, 0, 0);
        }   

        return newTime;
    }
u84six
  • 4,604
  • 6
  • 38
  • 65