最好的方法是在两者之间区分 timer灵感时间设定过去时间T,scheduleAtFixedRate将从T现在所有的任务中运行,schedule而该任务将只运行从现在开始计时。
public class HelloMain {
private static int count = 0;
public static void main(String[] args) {
Date date = new Date(System.currentTimeMillis() - 3000);
Timer timer = new Timer();
System.out.println("timer schedule before");
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
count++;
System.out.println(count + " timer task run " + Calendar.getInstance().getTime());
}
}, date, 1000);
System.out.println("timer schedule after");
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("timer cancel before");
timer.cancel();
System.out.println("timer cancel after");
}
}