本文介绍了每天在特定时间刷新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); } }推荐答案
下面是一段代码,该代码实现了 JB Nizeth的答案(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
发布评论