1

I have the code like this

cache = Caffeine.newBuilder()
        .build(this::loadData)
string loadData(String key) {
   return redishelpr.get(key);
}

What I want is run this loadData(key) function after every 15 minutes. I got aapproach of using @Scheduled(cron = "----") annotation but I just wanted to know if there is any other approach to do it on caffeine itself ??

I saw there is something like .schdeuler() on caffeine but could not get clear idea from docs

Rupesh
  • 840
  • 1
  • 12
  • 26
  • 2
    You should use a scheduled job. Caffeine's scheduler is for expiring entries when users require a prompt removal listener notification (e.g. close a websocket). For periodic cases its more straightforward to write the code explicitly, so it is not built in. – Ben Manes Oct 19 '22 at 18:27
  • Yeah I am thinking of same, that's simpler approach. Thanks for clearing out my doubt Ben! – Rupesh Oct 20 '22 at 19:58

1 Answers1

0

Something like this worked for me in a case where I wanted the cache to be refreshed every so often, irrespective of whether any values were being retrieved from the cache.

LoadingCache<Object, Object> myCache = Caffeine.newBuilder()
  //.refreshAfterWrite(5, TimeUnit.SECONDS)
  .build(key->"value");

Executors.newScheduledThreadPool(1).scheduleAtFixedRate(
  (new Runnable() { 
    @Override public void run() { 
      myCache.refresh("SOME_KEY");
    }
  }), 
  0, 5, TimeUnit.SECONDS
);

(With .refreshAfterWrite, otherwise attractive because .get's response is always fast, by default the cache seems not to refresh automatically unless there is some cache activity such as a ".get" call after its time period, meaning I think that the first call could have quite old values if there is a large gap between get calls).

phhu
  • 1,462
  • 13
  • 33