Skip to content

Instantly share code, notes, and snippets.

@wytten
Created May 22, 2013 17:37
Show Gist options
  • Select an option

  • Save wytten/5629385 to your computer and use it in GitHub Desktop.

Select an option

Save wytten/5629385 to your computer and use it in GitHub Desktop.
This is an inner class created in response to ScheduledExecutorService silently stopping when a task throws an Exception. See http://stackoverflow.com/questions/6894595/scheduledexecutorservice-exception-handling
private class ExecutorMonitor extends Thread {
public ExecutorMonitor() {
super("ExecutorMonitor");
}
@Override
public void run() {
while (enableAll || enabled) {
LOG.info("Starting scheduler for task '{}'", task.getName());
ScheduledFuture<?> scheduledTask = scheduledExecutorService.scheduleAtFixedRate(task, initialDelay, period,
timeUnit);
try {
scheduledTask.get();
} catch (ExecutionException e) {
// The task threw an exception
LOG.error(task.getName() + " failed", e.getCause());
if (stopOnError) {
LOG.warn("Scheduler for task '{}' stopping, must be restarted manually", task.getName());
return;
}
} catch (InterruptedException e) {
// Scheduler has been directed to stop via UI or JMX, or because of a system shutdown
scheduledTask.cancel(false);
LOG.info("Scheduler for task '{}' stopped", task.getName());
return;
}
}
LOG.info("NOT starting scheduler for task '{}', because it is disabled.", task.getName());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment