我将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时间过去了。
请帮助。
答案 0 :(得分:1)
根据古斯塔夫的建议:
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);
}
以上工作正常。现在,如果第一次是在我添加一天之前,那么它将仅在第二天调用。