All Downloads are FREE. Search and download functionalities are using the official Maven repository.

estonlabs.cxtl.common.stream.managed.PeriodicTimer Maven / Gradle / Ivy

There is a newer version: 1.4.14
Show newest version
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 - 2024 Weber Informatics LLC | Privacy Policy