Call a method at fixed time in Java

后端 未结 3 744
-上瘾入骨i
-上瘾入骨i 2020-12-30 18:15

How do I call a method at a particular time?

For example to call the method at 6:00 and 13:00.

I\'m working at a desktop application for Windows.

3条回答
  •  醉梦人生
    2020-12-30 18:41

    Have a look at the Timer and TimerTask classes. You can schedule a thread to execute at a specific time, or repeatedly.

    public class Alarm {
        Timer _timer;
    
        public Alarm() {
    
            // Create a Date corresponding to 10:30:00 AM today.
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 10);
            calendar.set(Calendar.MINUTE, 30);
            calendar.set(Calendar.SECOND, 0);
    
            Date alarmTime = calendar.getTime();
    
            _timer = new Timer();
            _timer.schedule(new AlarmTask(), alarmTime);
        }
    
        class AlarmTask extends TimerTask {
            /**
             * Called on a background thread by Timer
             */
            public void run() {
                // Do your work here; it's 10:30 AM!
    
                // If you don't want the alarm to go off again
                // tomorrow (etc), cancel the timer
                timer.cancel();
            }
        }
    }
    
    • Timer - http://java.sun.com/j2se/1.5.0/docs/api/java/util/Timer.html
    • TimerTask - http://java.sun.com/j2se/1.4.2/docs/api/java/util/TimerTask.html

提交回复
热议问题