Schedule a task for execution in Java


One of the methods in the Timer class is the void schedule(Timertask task, Date time) method. This method schedules the specified task for execution at the specified time. If the time is in the past, it schedules the task for immediate execution.

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

public void schedule(Timertask task, Date time)

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

IllegalArgumentExceptionThis exception is thrown if time.getTime() 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 or time is null.

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, new Date()); // scheduling the task
   }
   public void run() {
      System.out.println("Performing the given task");
   }
}

Output

Task is running

Updated on: 26-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements