0

It is not clear to me from the JavaDoc description of the java.util.concurrent.ScheduledExecutorService::scheduleAtFixedRate method, if the returned ScheduledFuture represents the same task for all
invocations of the scheduled action or not.

In other words, my scheduled actions will be performed for some undefined number of times (until I stop my application). Can I stop its execution at any time after any number of invocations by just saving this variable and canceling it?

This question is not only about actual implementation (which is by any means interesting to reveal), but also about proper understanding of the specification (what if I would like to provide my own implementation of the ScheduledExecutorService?).

Andremoniy
  • 34,031
  • 20
  • 135
  • 241
  • https://stackoverflow.com/questions/25049021/what-is-the-purpose-of-scheduledfuture-get-method-if-is-retrieved-from-the-sch – Sotirios Delimanolis Feb 14 '19 at 16:57
  • @SotiriosDelimanolis thanks, seems nearly same, but still doesn't contain the exact answer (though I guess that answer will be "yes", I am more worried about if it is following directly from the documentation or from the specific implementation of this interface?) – Andremoniy Feb 14 '19 at 20:38

1 Answers1

0

The returned ScheduledFuture should represent the ongoing task, including its recurrence.

We can know that this is the case by reading the following code snippet from the documentation of ScheduledExecutorService:

 import static java.util.concurrent.TimeUnit.*;
 class BeeperControl {
   private final ScheduledExecutorService scheduler =
     Executors.newScheduledThreadPool(1);

   public void beepForAnHour() {
     final Runnable beeper = new Runnable() {
       public void run() { System.out.println("beep"); }
     };
     final ScheduledFuture<?> beeperHandle =
       scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
     scheduler.schedule(new Runnable() {
       public void run() { beeperHandle.cancel(true); }
     }, 60 * 60, SECONDS);
   }
 }

The ScheduledFuture is used to cancel the task after an hour has elapsed. For this to function correctly, the ScheduledFuture cannot represent the initially submitted task, but rather must represent the ongoing recurrent task.

Michael Lowman
  • 3,000
  • 1
  • 20
  • 34