
estonlabs.cxtl.common.stream.managed.PeriodicTimer Maven / Gradle / Ivy
package estonlabs.cxtl.common.stream.managed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.Disposable;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* A utility that allows classes to register for a callback every 15 seconds.
* It is lazily instantiated so the timer will be activated on the first registration
*/
public final class PeriodicTimer {
private static final Logger LOGGER = LoggerFactory.getLogger(PeriodicTimer.class);
public static PeriodicTimer INSTANCE = new PeriodicTimer();
private final Map holders = new ConcurrentHashMap<>();
private PeriodicTimer() {
}
public synchronized Disposable register(long period, Runnable runnable){
Holder holder = holders.computeIfAbsent(period, Holder::new);
holder.runnable.add(runnable);
return () -> holder.runnable.remove(runnable);
}
private static class Holder {
private static final Timer timer = new Timer();
protected final Set runnable = Collections.newSetFromMap(new ConcurrentHashMap<>());
Holder(long period) {
Holder.timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
for(Runnable r: runnable) {
try{
r.run();
}catch(Exception e){
LOGGER.error("Error running timer",e);
}
}
}
}, 0, period);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy