[英]Java : Timer executing before the time of command
我想在特定時間執行 foo() 。 這是我的代碼:
public void scheduler() throws ParseException {
java.util.Timer _timer = new Timer();
TimerTask tt;
tt = new TimerTask() {
@Override
public void run() {
foo();
}
};
DateFormat dateFormatter = new SimpleDateFormat("HH:mm:ss");
java.util.Date date = dateFormatter.parse("14:26:00");
_timer.schedule(tt,date);
}
public void foo(){
System.out.println("Done");
}
但是 foo() 實際上是在我運行代碼本身時執行的,而不是在指定的時間。 請幫忙
public void scheduler() throws ParseException {
java.util.Timer _timer = new Timer();
TimerTask tt;
tt = new TimerTask() {
@Override
public void run() {
foo();
}
};
//Get the Date corresponding to 14:26:00 pm today.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 14);
calendar.set(Calendar.MINUTE, 26);
calendar.set(Calendar.SECOND, 0);
Date time = calendar.getTime();
_timer.schedule(tt,time);
}
public void foo(){
System.out.println("Done");
}
**Note:** _timer.schedule(tt, time):- Schedules the specified task for execution at the specified time. If the time is in the past, the task is scheduled for immediate execution.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.