Java Utility Library

Java Timer - schedule() Method



The java.util.Timer.schedule() method is used to schedule the specified task for execution at the specified time. If the time is in the past, the task is scheduled for immediate execution.

Syntax

public void schedule(TimerTask task,
                     Date time)

Parameters

task Specify the task to be scheduled.
time Specify the time at which task is to be executed.

Return Value

void type.

Exception

  • Throws IllegalArgumentException, if time.getTime() is negative.
  • Throws IllegalStateException, if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.
  • Throws NullPointerException, if task or time 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 time.

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
    //at current time and current date
    timer.schedule(tt, new Date());
  }
}

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