Assuming your cache is a directory with images in it, you can purge the cache like so:
private static void purge(File dir, long ttl) {
long minTime = System.currentTimeMillis()-ttl;
for (File file: dir.listFiles()) {
if (file.lastModified() < minTime) {
file.delete();
}
}
}
Now if you want to do this periodically, you need a timer:
private static final Timer TIMER = new Timer();
you can then schedule a task for purging:
TimerTask task = new TimerTask() {
@Override
public void run() {
purge(dir, ttl);
}
};
TIMER.schedule(task, period, period);
The task should be cancelled when not needed anymore.
You can put it all together in a class:
public class Cache implements Closeable {
private static final Timer TIMER = new Timer(true);
private final File dir;
private final long ttl;
private final TimerTask task;
public Cache(File dir, long ttl, long purgePeriod) {
this.dir = dir;
this.ttl = ttl;
task = new TimerTask() {
@Override
public void run() {
purge();
}
};
TIMER.schedule(task, purgePeriod, purgePeriod);
}
@Override
public void close() throws IOException {
task.cancel();
}
public synchronized void purge() {
long minTime = System.currentTimeMillis()-ttl;
for (File file: dir.listFiles()) {
if (file.isFile() && file.lastModified() < minTime) {
file.delete();
}
}
}
}