0

I'm having a little problem understanding how ScheduledThreadPoolExecutor works (I'm using SCA so don't bother with the annotations inside the code). That's part of the code from my Scheduler class:

@AllowsPassByReference
public ScheduledFuture<?> schedule(Task task)
{
    future=scheduler.scheduleAtFixedRate(task.getRunnableContent(), task.getDelay(), task.getPeriod(), TimeUnit.MILLISECONDS);
    return future;
}

@AllowsPassByReference
public void deschedule(Task task)
{
    scheduler.remove(task.getRunnableContent());
}

And that's part of the code from my Task class:

public void scheduleTask()
{
    if(!running)
    {
        future=scheduler.schedule(this);
        running=true;
    }
}

public void descheduleTask()
{
    if(running)
    {
        future.cancel(mayInterruptIfRunning);
        scheduler.deschedule(this);
        running=false;
    }
}

Now here's the big deal! Everywhere I looked people used cancel on ScheduledFutures and then used shutdown method on the scheduler, but I don't want to stop the scheduler. Let me explain a little better: in this application periodic tasks must be scheduled, stopped and re-scheduled individually at any time, so I need a way to interrupt a single task once it started running without having shutdown the whole scheduler service. I hope you can understand what I'm trying to do, any advice? Thanks :)

1 Answers1

0

When we cancel a periodic task, this task subsequent scheduling will be cancelled, but the scheduler itself will be running and can be used for scheduling another task.

If we call Future.cancel when the task is running then

a) Future.cancel(false) will not affect the running task

b) Future.cancel(true) will call Threed.interrupt on the task's thread, but whether the running task will stop or not depends on the task implementation. For instance the task may catch InterruptedException (if any) and continue working.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • Thanks for yout answer, at least now I know that the problems I'm having must have something to do with how SCA is managing my classes – user2163438 Mar 13 '13 at 03:26