gpt4 book ai didi

java - 定时器.schedule api : Why the timer task executes even the first time has passed

转载 作者:行者123 更新时间:2023-12-01 09:30:02 24 4
gpt4 key购买 nike

我将firstTime 设置为今天15:35,然后每天一次。但是当我今天启动应用程序时,即使在 15:35 之后,它也会立即启动任务。我不想这样。

 public void scheduleTimerTask() {

int taskStartTimeInSec = 56100;
Timer timer = new Timer();
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, taskStartTimeInSec);
Date firstTime = today.getTime();
System.out.println("firstTime is : "+ firstTime);
timer.schedule(new Task(), firstTime,
1000*60*60*24);
}

class Task extends TimerTask{

@Override
public void run() {
System.out.println("Thread Invoked at "+ new Date());

}

}

public static void main(String[] args) throws ParseException {
Test t = new Test();
t.scheduleTimerTask();
}


Output :
firstTime is : Thu Sep 15 15:35:00 IST 2016
Thread Invoked at Thu Sep 15 18:33:35 IST 2016

我希望如果我稍后开始(可能是 16:00),那么今天的任务不应执行,但应该在明天 15:35 执行。因为今天已经过了15点35分的时间了。

请帮忙。

最佳答案

根据古斯塔夫的建议:

public void scheduleTimerTask() {

int taskStartTimeInSec = 56100;
Timer timer = new Timer();
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, taskStartTimeInSec);
Date firstTime = today.getTime();
if(firstTime.before(new Date())){
today.add(Calendar.DATE, 1);
firstTime = today.getTime();
}
System.out.println("firstTime is : "+ firstTime);
timer.schedule(new Task(), firstTime,
1000*60*60*24);
}

以上效果很好。现在,如果第一次是在我添加一天之前,那么它将仅调用第二天。

关于java - 定时器.schedule api : Why the timer task executes even the first time has passed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39511920/

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