scheduling runnable tasks in java
Asked Answered
S

2

9

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

Sympathy answered 23/1, 2010 at 22:19 Comment(0)
S
9

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);
    }
  }
}
Spragens answered 23/1, 2010 at 22:26 Comment(0)
H
4

Pass the executor to the task, so that it can make manipulations with it:

SomeTask task = new SomeTask(executor);
Hort answered 23/1, 2010 at 22:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.