Java Timer - schedule() Method
The java.util.Timer.schedule() method is used to schedule the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.
Syntax
public void schedule(TimerTask task, long delay, long period)
Parameters
task |
Specify the task to be scheduled. |
delay |
Specify the delay in milliseconds before task is to be executed. |
period |
Specify the time in milliseconds between successive task executions. |
Return Value
void type.
Exception
- Throws IllegalArgumentException, if delay < 0, or delay + System.currentTimeMillis() < 0, or period <= 0.
- Throws IllegalStateException, if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.
- Throws NullPointerException, if task is null.
Example:
In the example below, the java.util.Timer.schedule() method is used to schedule the given task for execution for repeated fixed-delay execution, beginning 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 a //delay of 1000 milliseconds and then execution //repeated at a delay of 500 milliseconds timer.schedule(tt, 1000, 500); } }
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