How to schedule tasks in Java to run for repeated fixed-delay execution, beginning after the specified delay


One of the methods in the Timer class is the void schedule(TimerTask task, long delay, long period) method. This method schedules tasks for repeated fixed-delay execution, beginning after the specified delay.

In fixed-delay execution, each execution is scheduled with respect to the original execution time of the preceding execution. If an execution is delayed for a particular reason (case in point, garbage collection), the subsequent executions will be delayed as well.

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

public void schedule(TimerTask task, long delay, long period)

Here, task is the task to be scheduled, delay is the delay in milliseconds after which the task is executed and period is the time in milliseconds between successive task executions.

Here, task is the task to be scheduled, firstTime is the first time at which the task is executed and period is the time in milliseconds between successive task executions.

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

IllegalArgumentExceptionThis exception is thrown if delay is negative or delay + System.currentTimeMillis() is negative or period is <=0
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, long period) 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
      // scheduling the task for repeated fixed-delay execution, beginning after the specified delay
      timer.schedule(task, 800, 1000);
   }
}

Output

Task is running
Task is running
Task is running
Task is running
Task is running
Task is running
Task is running
Task is running
Task is running

Updated on: 25-Jun-2020

965 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements