每天在特定时间刷新Guava LoadingCache

时间:2016-06-05 13:51:39

标签: caching loading guava

我需要在特定时间每天刷新我的缓存,在我的情况下,在午夜。我有办法用Guava LoadingCache做到这一点吗? 到目前为止,我只在一天之后更新缓存,使用下一个代码:

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 个答案:

答案 0 :(得分:3)

这是一个实现JB Nizeth's回答(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);