long timerId = timeoutCounter.getAndIncrement();
final InternalTimerHandler task = new InternalTimerHandler(timerId, handler, periodic);
final Runnable wrapped = context.wrapTask(task);
final Runnable toRun;
final EventLoop el = context.getEventLoop();
if (context instanceof EventLoopContext) {
toRun = wrapped;
} else {
// On worker context
toRun = new Runnable() {
public void run() {
// Make sure the timer gets executed on the worker context
context.execute(wrapped);
}
};
}
Future<?> future;
if (periodic) {
future = el.scheduleAtFixedRate(toRun, delay, delay, TimeUnit.MILLISECONDS);
} else {
future = el.schedule(toRun, delay, TimeUnit.MILLISECONDS);
}
task.future = future;
timeouts.put(timerId, task);
context.addCloseHook(task);
return timerId;