apycazo
5/19/2013 - 1:19 PM

Scheduler wrapper in Java

Scheduler wrapper in Java

import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class Scheduler {
    private int maxThreadsInPool;
    private ScheduledExecutorService scheduler;
    private LinkedHashMap<String,ScheduledFuture<?>> map;
    
    public Scheduler (int maxThreadsInPool) {
        this.maxThreadsInPool = maxThreadsInPool;
        this.scheduler = Executors.newScheduledThreadPool(maxThreadsInPool);
        this.map = new LinkedHashMap<>();
    }
    
    public ScheduledExecutorService getScheduler () {
        return scheduler;
    }
    
    public int getMaxThreadsInPool () {
        return this.maxThreadsInPool;
    } 
    
    public boolean schedule (String name, Runnable job, int period, TimeUnit timeUnit) {
        return schedule(name,job,period,period,timeUnit);
    }
    
    public boolean schedule (String name, Runnable job, int delay, int period, TimeUnit timeUnit) {
        if (this.map.containsKey(name)) {
            return false;
        }
        // command, delay, period, timeunit
        ScheduledFuture<?> scheduledJob = scheduler.scheduleAtFixedRate(job, delay, period, timeUnit);
        this.map.put(name, scheduledJob);
        return true;
    }
    
    public boolean scheduleOnce (String name, Runnable job, int delay, TimeUnit timeUnit) {
        if (this.map.containsKey(name)) {
            return false;
        }
        ScheduledFuture<?> scheduledJob = scheduler.schedule(job, delay, timeUnit);
        this.map.put(name, scheduledJob);
        return true;
    }
    
    public boolean stopJob (String name, boolean interrupt) {
        if (this.map.containsKey(name)) {
            ScheduledFuture<?> scheduledJob = this.map.get(name);
            scheduledJob.cancel(interrupt);
            map.remove(name);
            return true;
        }
        else {
            return false;
        }
    }
    
    public void shutdown () {
        this.scheduler.shutdown();
    }
    
    public List<Runnable> shutdownNow() {
        return this.scheduler.shutdownNow();
    }
    
}