Search code examples
javatimerschedulingtimer-jobs

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


Solution

  • 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);
        }
      }
    }