2

I have:

private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();

that runs a runnable task:

executorService.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS);

But it appears that executorService doesn't have a cancel method (wtf, why?), shutting it down isn't an option and I'm doing something fairly simple so using Executors.newScheduledThreadPool (which does have cancel()) is a bit of an overkill.

Is there a way to properly stop the execution of the task?

PS: I searched before I asked and I really don't think this hack is the correct way.

Community
  • 1
  • 1
shinzou
  • 5,850
  • 10
  • 60
  • 124
  • You are looking for one of the `shutDown*()` methods. – fge Sep 03 '16 at 12:31
  • I have only `shutdownNow` and `shutDown` from `executorService` and both will also prevent future tasks, but I want future tasks. @fge – shinzou Sep 03 '16 at 12:34

1 Answers1

3

executorService.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS); returns a ScheduledFuture<V>, which does have a cancel(boolean) method. The correct way to cancel it is to cancel it through the future.

EDIT: However I believe this cannot stop a task while it is executing, only prevent future executions. Using the boolean flag requires the task to be aware of the Thread.isInterrupted() system.

Kiskae
  • 24,655
  • 2
  • 77
  • 74
  • So I should have a data member for `ScheduledFuture>` and populate it when calling `scheduleAtFixedRate`? because I need to stop the task from the task itself which is in the runnable wrapper. – shinzou Sep 03 '16 at 12:37
  • If the only thing you need is the ability to cancel, just throw an exception from within the `.run()` method. The contract explicitly says this will stop any future executions. – Kiskae Sep 03 '16 at 12:46
  • But that's not what exceptions are for no? and exceptions are considered "runtime heavy" so isn't this little expensive? – shinzou Sep 03 '16 at 12:51
  • If you don't want to use exceptions then you'll need some sort of wrapper that makes the outer future available to the task, but that will be its own sort of pain implementing. – Kiskae Sep 03 '16 at 14:02
  • will this remove the task from the scheduler . Or will this only make the the `isDone()` method return true. I am asking this because I am using `ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); ScheduledFuture> future = scheduler.scheduleAtFixedRate` – Ismail Iqbal Feb 14 '17 at 08:17