Java Utility Library

Java Timer - schedule() Method



The java.util.Timer.schedule() method is used to schedule the specified task for execution after the specified delay.

Syntax

public void schedule(TimerTask task,
                     long delay)

Parameters

task Specify the task to be scheduled.
delay Specify the delay in milliseconds before task is to be executed.

Return Value

void type.

Exception

  • Throws IllegalArgumentException, if delay is negative, or delay + System.currentTimeMillis() is negative.
  • 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 at 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() {
        for (int i = 0; i <= 5; i++) {
          System.out.println("Working on the task.");
        }
        System.out.println("Task is finished.");
      };
    };
    
    //scheduling the task to be executed
    //after a delay of 1000 milliseconds
    timer.schedule(tt, 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.
Working on the task.
Working on the task.
Task is finished.

❮ Java.util - Timer