我有三个与Timer关联的计时器任务,它们被安排在不同的时间间隔运行。我的要求是如果其中一个计时器任务完成了任务,我需要取消与之关联的其他计时器。还有可能将计时器任务名称发送回调用方法吗?
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();
}
}
}
答案 0 :(得分:1)
更改MyTimerTask
的构造函数以接受timer
作为参数并将其分配给字段。任务完成后,您只需在计时器上执行cancel
。
从TimerTask
你无法获得计划它的计时器。