Skip to content

Instantly share code, notes, and snippets.

@InputNeuron
Created May 2, 2015 23:36
Show Gist options
  • Select an option

  • Save InputNeuron/34a67c24ca9ce0574c04 to your computer and use it in GitHub Desktop.

Select an option

Save InputNeuron/34a67c24ca9ce0574c04 to your computer and use it in GitHub Desktop.
public final class Scheduler extends ServiceSupport {
private final String name;
private Timer timer;
private final HashMap<Runnable, TimerTask> timerTasks = new HashMap<Runnable, TimerTask>();
public Scheduler(String name) {
this.name = name;
}
public synchronized void executePeriodically(final Runnable task, long period) {
TimerTask timerTask = new SchedulerTimerTask(task);
timer.schedule(timerTask, period, period);
timerTasks.put(task, timerTask);
}
public synchronized void cancel(Runnable task) {
TimerTask ticket = timerTasks.remove(task);
if (ticket != null) {
ticket.cancel();
timer.purge(); // remove cancelled TimerTasks
}
}
public synchronized void executeAfterDelay(final Runnable task, long redeliveryDelay) {
TimerTask timerTask = new SchedulerTimerTask(task);
timer.schedule(timerTask, redeliveryDelay);
}
public void shutdown() {
timer.cancel();
}
@Override
protected synchronized void doStart() throws Exception {
this.timer = new Timer(name, true);
}
@Override
protected synchronized void doStop(ServiceStopper stopper) throws Exception {
if (this.timer != null) {
this.timer.cancel();
}
}
public String getName() {
return name;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment