ehcache based on date

前端 未结 3 885
温柔的废话
温柔的废话 2021-02-08 11:58

I\'m working with ehcache 2.5.4.

I have an object that needs to be cached through out the day and refreshed with a new value at 00:00am every day.

Currently with

3条回答
  •  情书的邮戳
    2021-02-08 12:34

    EHCache only supports eviction after a certain period of time (either being in the cache or due to inactivity). However, you should be able to accomplish that fairly easily by scheduling the removal with something like this:

        Timer t = new Timer(true);
        Integer interval = 24 * 60 * 60 * 1000; //24 hours
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
    
    
        t.scheduleAtFixedRate( new TimerTask() {
                public void run() {
                    Cache c = //retrieve cache                  
                    c.removeAll();                                            
                }
            }, c.getTime(), interval);
    

    This basic example uses the Java Timer class to illustrate, but any scheduler could be utilized. Every 24 hours, starting from midnight - this would run and remove all the elements from the specified cache. The actual run method could be modified to remove elements matching a certain criteria as well.

    You'd just need to make sure you start it when the application is started.

提交回复
热议问题