package uu.mal.skate.threading; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public abstract class PausableScheduledTask { public abstract void task(); public abstract long getInitialDelay(); public abstract long getPeriodDelay(); public abstract TimeUnit getTimeUnit(); private ScheduledExecutorService executor = null; private volatile boolean isPaused = false; Runnable scheduler = new Runnable() { @Override public void run() { if (!isPaused) task(); } }; public void start() { if (executor == null || executor.isShutdown()) { executor = Executors.newSingleThreadScheduledExecutor(); executor.scheduleAtFixedRate(scheduler, getInitialDelay(), getPeriodDelay(), getTimeUnit()); } else { resume(); } } public void pause() { isPaused = true; } public void resume() { isPaused = false; } public void stop() { if(executor != null) { executor.shutdownNow(); executor = null; } } }