Use annotations @Scheduled with a cron expression and @CacheEvict with allEntries = true like this:
/*
* This clears the entire cache called "myCache" everyday,
* at 00.00 (am) in the time zone of the server.
*/
@Scheduled(cron = "0 0 0 * * ?")
@CacheEvict(value = "myCache", allEntries = true)
public void clearMyCache() {}
If you want to add logic before clearing the cache you can do so in the method body:
/*
* This clears the entire cache called "myCache" everyday,
* at 00.00 (am) in the time zone of the server.
*/
@Scheduled(cron = "0 0 0 * * ?")
@CacheEvict(value = "myCache", allEntries = true)
public void clearMyCache() {
// Add logic here
log.debug("Clearing myCache now");
}
The CacheEvict hapens after your code runs and only if it doesn't throw any exceptions. You can change that by adding "beforeInvocation = true" in which case it evicts the cache first, then runs your code.