Java Utility Library

Java Timer - purge() Method



The java.util.Timer.purge() method is used to remove all canceled tasks from this timer's task queue.

Syntax

public int purge()

Parameters

No parameter is required.

Return Value

Returns the number of tasks removed from the queue.

Exception

NA.

Example:

In the example below, the java.util.Timer.purge() method is used to remove all canceled tasks from the given timer's task queue.

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() {
        for (int i = 0; i <= 10; i++) {
          System.out.println("Working on the task.");
          if(i==5) {
            System.out.println("Stop the task.");
            timer.cancel();
            break;
          }
        }
        // purging the timer 
        System.out.println("The Purge value:" + timer.purge()); 
      };
    };
    
    //scheduling the task to be executed  
    //after a delay of 100 milliseconds
    timer.schedule(tt, 100);
  }
}

The output of the above code will be:

Working on the task.
Working on the task.
Working on the task.
Working on the task.
Working on the task.
Working on the task.
Stop the task.
The Purge value:0

❮ Java.util - Timer