3

I'm developing a Java EE 7 application on wildfly 8.2 and need to run a periodic background task. I inject an executor service and schedule a task, this part is working fine:

@Resource
private ManagedScheduledExecutorService executorService;

...

executorService.scheduleWithFixedDelay(() -> {
  try {
    // do some stuff
  } catch (Throwable t) {
    log.error("Error", t);
  }
}, 0, 1, TimeUnit.MINUTES);

Now the (actually nice) feature is that upon redeploy the scheduled task is saved and therefore is still scheduled in the new deployment.

But how can I detect if the task is already scheduled to avoid scheduling it multiple times?

I tried to use a ScheduledFutureand cancel the task on @PreDestroy and @PrePassivate

reloadTreeFuture = executorService.scheduleWithFixedDelay(() -> {

...

@PreDestroy
@PrePassivate
protected void shutdown() {
  reloadTreeFuture.cancel(true);
}

This is working fine as long as the corresponding task is not executing at the very moment the cancel is fired. Since the task is long running and running frequently the chance of hitting it in the middle of an execution is somewhat high.

If the cancel is fired while the task is still executing the cancel seems to do nothing. It immediatly returns and the method ScheduledFuture.isDone() also returns true but from the logs I can see the task is still executing in the background until it hits a point where it needs an injected Bean which is not available due to the undeployment process. The process then ends with org.jboss.msc.service.ServiceNotFoundException - but is still scheduled.

  reloadTreeFuture.cancel(true);
  while (!reloadTreeFuture.isDone()) {
    Thread.sleep(200); // I know this is bad - it's just for testing
  }

So basic question: how can I make sure the task is not scheduled twice (or even more)?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Lasrik
  • 589
  • 1
  • 8
  • 22

1 Answers1

0

You could write down the id of each task and check them before executing. Of course this may be not a best solution, but it works.

Sefler
  • 2,237
  • 5
  • 19
  • 29