Set a timer for a task to run at a specific time




This Java tip illustrates a method of scheduling a timer for a task to run at a certain time.
Developer may use this code if there is a need to execute or repeat a task in an application at a predefined interval of time.

class TimerDemo {
    public static void main(String[] arg) {
        int interval = 10000; // 10 sec
        Date timeToRun = new Date(System.currentTimeMillis() + interval);
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                // Task here . . .
            }
        }, timeToRun);
    }
}

The above code demonstrates how to use the Timer and TimerTask classes in Java to schedule a task to run after a specific delay.

The TimerDemo class contains a main method that creates a Timer object and schedules a TimerTask to run after a specified delay of 10 seconds. Here's how the code works:

1. The variable interval is set to 10,000 milliseconds (or 10 seconds).
2. The variable timeToRun is set to the current time plus the delay interval using the Date constructor. This creates a Date object that represents the time at which the task should be executed.
3. A new Timer object is created using the default constructor.
4. The schedule method of the Timer object is called, passing in a new TimerTask object and the timeToRun object as arguments. The TimerTask object contains the code that should be executed when the timer fires.
5. The run method of the TimerTask is called by the Timer when the specified delay interval has elapsed.

In the code example, the run method of the TimerTask is left empty (commented out), but this is where you would add the code that you want to execute after the specified delay. When the Timer fires, it creates a new thread and executes the run method of the TimerTask in that thread.

This code can be used to schedule periodic tasks or to execute one-time tasks after a delay. The Timer and TimerTask classes are part of the java.util package in Java and are available in all versions of the language.


Previous Post Next Post