Schedule a task for execution in Java after a given delay

Java 8Object Oriented ProgrammingProgramming

One of the methods in the Timer class is the void schedule(Timertask task, long delay) method. This method schedules the specified task for execution after the specified delay.

Declaration −The java.util.Timer.schedule(Timertask task, long delay) is declared as follows −

public void schedule(Timertask task, long delay)


There are few exceptions thrown by the schedule(Timertask task, long delay) method. They are as follows −

IllegalArgumentExceptionThis exception is thrown if delay is negative, or delay + System.currentTimeMillis() is negative.
IllegalStateExceptionThis exception is thrown if task was scheduled or cancelled beforehand, timer was cancelled, or timer thread terminated.
NullPointerExceptionThis exception is thrown if the task is null.

Let us see a program illustrating the use of the void schedule(TimerTask task, long delay) method −

Example

 Live Demo

import java.util.*;
   class MyTask extends TimerTask {
      public void run() {
         System.out.println("Task is running");
      }
   }
   public class Example {
      public static void main(String[] args) {
         Timer timer = new Timer(); // creating timer
         TimerTask task = new MyTask(); // creating timer task
         timer.schedule(task,3000); // scheduling the task after the delay
      }
      public void run() {
         System.out.println("Performing the given task");
      }
}

Output

Task is running
raja
Published on 08-Jan-2019 06:47:19
Advertisements