Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 580
bushman Avatar asked Jan 23 '10 22:01

bushman


2 Answers

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);
    }
  }
}
like image 177
Adamski Avatar answered Sep 27 '22 20:09

Adamski


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

SomeTask task = new SomeTask(executor);
like image 20
Bozho Avatar answered Sep 27 '22 19:09

Bozho