定时器和定时器任务

Timer and Timer Task

我有三个与计时器关联的计时器任务,它们被安排在不同的时间间隔 运行。我的要求是,如果其中一个定时器任务完成了任务,我需要取消与其关联的其他定时器。并且是否可以将定时器任务名称发送回调用方法?

package sample;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class MyTimerTask extends TimerTask {
  private String name;
  MyTimerTask(String name){
    this.name =  name;
  }
  @Override
  public void run() {
      System.out.println("Timer task started at:"+new Date());
      completeTask();
      System.out.println("Timer task finished at:"+new Date());
  }

  private void completeTask() {
      try {
        System.out.println("In Timer Task");
          //assuming it takes 20 secs to complete the task
          Thread.sleep(20000);
          // Here i need to cancel other timer task and return name.
      } catch (InterruptedException e) {
          e.printStackTrace();
      }
  }

  public static void main(String args[]){
      TimerTask timerTask = new MyTimerTask("T1");
      TimerTask timerTask2 = new MyTimerTask("T2");
      TimerTask timerTask3 = new MyTimerTask("T3");
      //running timer task as daemon thread
      Timer timer = new Timer(true);
      timer.scheduleAtFixedRate(timerTask, 0, 10*1000);

      timer.scheduleAtFixedRate(timerTask2, 0, 20*1000);
      timer.scheduleAtFixedRate(timerTask3, 0, 30*1000);

      //cancel after sometime
      try {
          Thread.sleep(120000);
      } catch (InterruptedException e) {
          e.printStackTrace();
      }
      timer.cancel();
      System.out.println("TimerTask cancelled");
      try {
          Thread.sleep(30000);
      } catch (InterruptedException e) {
          e.printStackTrace();
      }
  }

}

更改 MyTimerTask 的构造函数以接受 timer 作为参数并将其分配给字段。任务完成后,您可以在计时器上执行 cancel

TimerTask 中您无法获得安排它的计时器的句柄。