Refresh Guava LoadingCache everyday at a specific time

房东的猫 提交于 2020-06-26 05:33:23

问题


I need that my cache be refreshed everyday at a specific time, in my case, at midnight. I have way to do this with Guava LoadingCache? So far I only got the cache be renewed after a day, with the next code:

private final LoadingCache<String, Long> cache = CacheBuilder.newBuilder()
    .refreshAfterWrite(1, TimeUnit.DAYS)
    .build(new CacheLoader<String, Long>() {
        public Long load(String key) {
            return getMyData("load", key);
        }
}

回答1:


Here's a code snipped that implements JB Nizeth's answer (Java 8):

long millisUntilMidnight = Duration
            .between(LocalDateTime.now(), LocalDateTime.of(LocalDate.now().plusDays(1), LocalTime.MIDNIGHT))
            .toMillis();
Executors.newSingleThreadScheduledExecutor()
            .scheduleAtFixedRate(() -> cache.invalidateAll(), millisUntilMidnight,
            TimeUnit.DAYS.toMillis(1), TimeUnit.MILLISECONDS);


来源:https://stackoverflow.com/questions/37642678/refresh-guava-loadingcache-everyday-at-a-specific-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!