问题
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