我正在使用java.util.Timer
类,我正在使用它的schedule方法执行一些任务,但在执行6次后,我必须停止它的任务。
我该怎么做?
在某个地方保留计时器的引用,并使用:
timer.cancel();
timer.purge();
为了停止正在进行的操作,你可以将此代码放置在正在执行的任务中,并使用 static int
计算循环次数,例如:
private static int count = 0;
public static void run() {
count++;
if (count >= 6) {
timer.cancel();
timer.purge();
return;
}
... perform task here ....
}
您应该停止定时器上已安排的任务: 您的定时器:
Timer t = new Timer();
TimerTask tt = new TimerTask() {
@Override
public void run() {
//do something
};
};
t.schedule(tt,1000,1000);
tt.cancel();
t.cancel(); //In order to gracefully terminate the timer thread
在特定的毫秒时间后唤醒后,终止计时器。
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
System.out.println(" Run spcific task at given time.");
t.cancel();
}
}, 10000);
Timer
和TimerTask
类已被取代。学习使用Java 5+中添加的Executors框架。请参阅Oracle的Java教程。 - Basil Bourque