我使用Timer在5秒后调用方法。当我在5秒之前再次调用相同的方法时,前一个被调用的方法应该被取消。怎么做?
由于
答案 0 :(得分:0)
您无需再次使用TimerTask重新启动Timer。你可以像这样安排它。
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//Called each time when 1000 milliseconds (1 second) (the period parameter)
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);
如果您需要随时取消计时器,可以使用此功能。
timer.cancel(); // Terminates this timer, discarding any currently scheduled tasks.
timer.purge(); // Removes all cancelled tasks from this timer's task queue.