Cancel a scheduled fixed rate task depending on the result of the task

I'm using Spring's TaskScheduler to schedule a periodic task.

ScheduledFuture scheduleAtFixedRate(Runnable task, long period);

I understand that I can call cancel() on the ScheduledFuture to stop the recurring task from being executed. But I'd like to cancel the recurring scheduled task depending on the result of the execution of the task, and am not sure how to best do that.

Does the ScheduledFuture give me access to the result of EACH executed task? Or do I need some sort of task listener that can keep a reference to this ScheduledFuture, and cancel it that way? Or something else?


Ok it looks like it is possible, but there is probably a better approach.

Since a recurring job only takes a Runnable (with a void return type) there is no way to return the result of the task. So the only way to stop the recurring task is to make the task perform a side-effect, eg adding a stop message to a queue. Then a separate thread would need to monitor this queue, and it could cancel the job once it sees the message.

Very messy and complicated.

A better alternative is to create a normal (one time) scheduled task. The task itself can then decide whether or not it needs to schedule another task, and can do the scheduling of the next task itself.


Keep a handle or the original fixed rate ScheduledFuture , then when the condition arises where you want to cancel it, schedule a new task that does the cancel.

You might also be able to do something with a RunnableScheduledFuture .

From the ScheduledExecutorService docs

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html

 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);
   }
 }
链接地址: http://www.djcxy.com/p/74904.html

上一篇: java.util.TimerTask cancel()方法的确切语义

下一篇: 根据任务的结果取消预定的固定费率任务