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 after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period.

Syntax

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

Parameters

task Specify the task to be scheduled.
delay Specify the delay in milliseconds before task is to be executed.
period Specify the time in milliseconds between successive task executions.

Return Value

void type.

Exception

  • Throws IllegalArgumentException, if delay < 0, or delay + System.currentTimeMillis() < 0, or period <= 0.
  • Throws IllegalStateException, if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.
  • Throws NullPointerException, if task 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 after the specified delay.

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 after a
    //delay of 1000 milliseconds and then execution
    //repeated at a period of 500 milliseconds
    timer.scheduleAtFixedRate(tt, 1000, 500);
  }
}

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