Java:在命令时间之前执行计时器

问题描述

我想在特定时间执行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.