Monday, December 30, 2024
Google search engine
HomeLanguagesJavaTimer purge() method in Java with Examples

Timer purge() method in Java with Examples

The purge() method of Timer class in Java is used to remove all the cancelled tasks from this queue of the Timer. The behaviour of the time remains unaffected by the calling of this method.

Syntax:

public int purge()

Parameters: The method does not take any parameters.

Return Value: The method returns the number of tasks that have been removed from the queue.

Below programs illustrate the working of purge() method in Java:

Program 1:




// Java code to illustrate purge()
  
import java.util.*;
  
public class Java_Timer_Demo {
    public static void main(String args[])
    {
  
        // Creating the timer task, timer
        Timer time = new Timer();
  
        TimerTask timetask = new TimerTask() {
  
            public void run()
            {
  
                for (int i = 1; i <= 15; i++) {
  
                    System.out.println("Working on the task");
  
                    if (i >= 7) {
                        System.out.println("Stopping the task");
                        time.cancel();
                        break;
                    }
                }
  
                // purging the timer
                System.out.println("The Purge value:"
                                   + time.purge());
            };
        };
  
        time.schedule(timetask, 1500, 2000);
    }
}


Output:

Working on the task
Working on the task
Working on the task
Working on the task
Working on the task
Working on the task
Working on the task
Stopping the task
The Purge value:0

Program 2:




// Java code to illustrate purge()
  
import java.util.*;
  
public class Java_Timer_Demo {
  
    public static void main(String args[])
    {
  
        // Creating the timer task, timer
        Timer time = new Timer();
  
        TimerTask timetask = new TimerTask() {
            public void run()
            {
  
                for (int i = 1; i <= 5; i++) {
  
                    System.out.println("Working on the task");
  
                    if (i >= 2) {
  
                        System.out.println("Stopping the task");
                        time.cancel();
                    }
                }
  
                // Purging the timer
                System.out.println("The Purge value:"
                                   + time.purge());
            };
        };
  
        time.schedule(timetask, 1, 1000);
    }
}


Output:

Working on the task
Working on the task
Stopping the task
Working on the task
Stopping the task
Working on the task
Stopping the task
Working on the task
Stopping the task
The Purge value:0

Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Timer.html#purge–

RELATED ARTICLES

Most Popular

Recent Comments