Java Utility Library

Java Timer - scheduleAtFixedRate() Method



The java.util.Timer.scheduleAtFixedRate() method is used to schedule the specified task for repeated fixed-rate execution, beginning at the specified time. Subsequent executions take place at approximately regular intervals, separated by the specified period.

Syntax

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

Parameters

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

Return Value

void type.

Exception

  • Throws IllegalArgumentException, if firstTime.getTime() < 0 or period <= 0.
  • Throws IllegalStateException, if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.
  • Throws NullPointerException, if task or firstTime is null.

Example:

In the example below, the java.util.Timer.scheduleAtFixedRate() method is used to schedule the given task for repeated fixed-rate execution, beginning 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() {
        System.out.println("Working on the task.");
      };
    };
    
    //scheduling the task to be executed at current
    //time and current date, then repeated at a 
    //period of 1000 milliseconds
    timer.scheduleAtFixedRate(tt, new Date(), 1000);
  }
}

The output of the above code will be:

Working on the task.
Working on the task.
Working on the task.
Working on the task. 
and so on ...

❮ Java.util - Timer