Java Timer - schedule() Method
The java.util.Timer.schedule() method is used to schedule the specified task for repeated fixed-delay execution, beginning at the specified time. Subsequent executions take place at approximately regular intervals, separated by the specified period.
Syntax
public void schedule(TimerTask task, Date firstTime, long period)
Parameters
task |
Specify the task to be scheduled. |
firstTime |
Specify the First time at which task is to be executed. |
period |
Specify the time in milliseconds between successive task executions. |
Return Value
void type.
Exception
- Throws IllegalArgumentException, if firstTime.getTime() < 0, or period <= 0.
- Throws IllegalStateException, if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.
- Throws NullPointerException, if task or firstTime is null.
Example:
In the example below, the java.util.Timer.schedule() method is used to schedule the given task for execution for the first time at the specified time and repeated the execution after the specified delay.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a timer Timer timer = new Timer(); //creating a timertask TimerTask tt = new TimerTask() { public void run() { System.out.println("Working on the task."); }; }; //scheduling the task to be executed at //current time and current date, and then //executed at a delay of 1000 milliseconds timer.schedule(tt, new Date(), 1000); } }
The output of the above code will be:
Working on the task. Working on the task. Working on the task. Working on the task. and so on ...
❮ Java.util - Timer