简体   繁体   中英

scheduling runnable tasks in java

I am following up an interesting question on so, on usage of ScheduledThreadPoolExecutor for some repeating task.

Scheduling this object returns a ScheduledFuture object which one can use to cancel the next run of the task.

One thing to note here is the task itself is completely decoupled from the schedule--

ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1);
ScheduledFuture nextSchedule = 
    executor.schedule(task, 60000, TimeUnit.MILLISECONDS);

where-

SomeTask task = new SomeTask();

So the task itself is not aware of the schedule. Please enlighten if there is a way to get the task to cancel and create a new schedule for itself.

Thanks

There's no reason why the task cannot reference the ScheduledExecutorService and schedule itself to run again if required:

// (Need to make variable final *if* it is a local (method) variable.)
final ScheduledExecutorService execService = Executors.newSingleThreadScheduledExecutor();

// Create re-usable Callable.  In cases where the Callable has state
// we may need to create a new instance each time depending on requirements.
Callable<Void> task = new Callable() {
  public Void call() {
    try {
      doSomeProcessing();
    } finally {
      // Schedule same task to run again (even if processing fails).
      execService.schedule(this, 1, TimeUnit.SECONDS);
    }
  }
}

executor传递给任务,以便它可以使用它进行操作:

SomeTask task = new SomeTask(executor);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM