gpt4 book ai didi

java - 当最后一个任务还没有完成时,如何让 Timer 跳过任务?

转载 作者:行者123 更新时间:2023-11-30 11:27:09 30 4
gpt4 key购买 nike

这是代码片段:

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

谁能帮帮我?非常感谢!

最佳答案

你应该使用 fixed-delay execution相反,它根据前一个任务的完成时间而不是开始时间开始下一个任务。如果 Timer 不支持您的需要,请查看功能更强大的调度库,如 Quartz .

关于java - 当最后一个任务还没有完成时,如何让 Timer 跳过任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19461861/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com