这是代码片段:
Timer t = new Timer();
TimerTask task = new TimerTask() {
int i = 0;
int longTimeJobPoint = 2;
@Override
public void run() {
System.out.println(new Date());
if(++i == longTimeJobPoint) {
try {
System.out.println("sleeping time...");
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
//every 10 sec
t.scheduleAtFixedRate(task, new Date(), 10000);
结果如下:
Sat Oct 19 10:44:59 CST 2013
Sat Oct 19 10:45:09 CST 2013
sleeping time...
Sat Oct 19 10:45:39 CST 2013 //piled task
Sat Oct 19 10:45:39 CST 2013 //piled task
Sat Oct 19 10:45:39 CST 2013
Sat Oct 19 10:45:49 CST 2013
我们可以看到,当Thread.sleep()
延迟 30 秒时,定时定时器会堆积每 10 秒应该调用的任务。我想要的是跳过因为最后一个任务还没有完成而延迟的任务。输出应该是这样的:
Sat Oct 19 10:44:59 CST 2013
Sat Oct 19 10:45:09 CST 2013
sleeping time...
Sat Oct 19 10:45:39 CST 2013
Sat Oct 19 10:45:49 CST 2013
谁能给我一些帮助?非常感谢!