How to schedule tasks in Java to run for repeated fixed-rate execution, beginning at the specified time

Java 8Object Oriented ProgrammingProgramming

One of the methods the Timer class is void scheduleAtFixedRate(TimerTask task, Date firstTime, long period). This method schedules the specified task for repeated fixed-rate execution, beginning at the specified time.

In fixed-rate execution, each execution is scheduled with respect to the scheduled run time of the initial execution. Fixed-rate execution is apt for repetitive activities that are respond to absolute time. Likewise,fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain in sync.

Declaration − The java.util.Time.scheduleAtFixedRate(TimerTask task, Date firstTime, long period) method is declared as follows −

public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)

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 scheduleAtFixedRate(Timertask task, Date firstTime, long period) method. They are as follows −

IllegalArgumentExceptionThis exception is thrown if firstTime.getTime 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 an example showing how to schedule tasks in Java to run for repeated fixed-rate execution, beginning at the specified time −

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.scheduleAtFixedRate(task,new Date(),2000);
      // scheduling the task at the specified time at fixed-rate
   }
}

Output

Task is running
Task is running
Task is running
Task is running
Task is running
raja
Published on 09-Jan-2019 10:24:27
Advertisements