本文介绍了每天在特定时间刷新Guava LoadingCache的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要每天在特定时间(例如我的午夜)刷新缓存。我有办法用Guava LoadingCache做到这一点吗?
到目前为止,我只需要在一天后使用以下代码更新缓存即可。

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


推荐答案

下面是一段代码,该代码实现了(Java 8 ):

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

这篇关于每天在特定时间刷新Guava LoadingCache的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-08 00:19