8

いくつかの繰り返しタスクでのScheduledThreadPoolExecutorの使用について、興味深い質問をフォローアップしています。

このオブジェクトをスケジュールすると、ScheduledFutureオブジェクトが返されます。このオブジェクトを使用して、タスクの次の実行をキャンセルできます。

ここで注意すべきことの1つは、タスク自体がスケジュールから完全に切り離されていることです。

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

どこ-

SomeTask task = new SomeTask();

したがって、タスク自体はスケジュールを認識していません。タスクをキャンセルして、それ自体の新しいスケジュールを作成する方法があるかどうかを教えてください。

ありがとう

4

2 に答える 2

7

ScheduledExecutorServiceタスクがを参照できず、必要に応じて実行するようにスケジュールを設定できない理由はありません。

// (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);
    }
  }
}
于 2010-01-23T22:26:55.753 に答える
4

タスクにを渡してexecutor、タスクが操作できるようにします。

SomeTask task = new SomeTask(executor);
于 2010-01-23T22:29:14.627 に答える