1

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.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
nicky
  • 3,810
  • 9
  • 35
  • 44

3 Answers3

10

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();
        }
    }
}
fospathi
  • 537
  • 1
  • 6
  • 7
Scott Smith
  • 3,900
  • 2
  • 31
  • 63
4

An alternative to to use Quartz. It's effectively the same as Timer or TimerTask, but it does allow for a description of what must run using a cron style syntax.

gpampara
  • 11,989
  • 3
  • 27
  • 26
3

Since Java 1.5 there is a preferable way, if you need to be more strict: ScheduledThreadPoolExecutor:

This class is preferable to Timer when multiple worker threads are needed, or when the additional flexibility or capabilities of ThreadPoolExecutor (which this class extends) are required.

There you choose between scheduleAtFixedRate() and scheduleWithFixedRate(). More details on the usage can be found in the linked javadoc.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140