Tuesday, 5 February 2019

How to remove all canceled tasks from the timer's task queue using purge() method of Timer class


Click here to watch on Youtube:
https://www.youtube.com/watch?v=rQd1BZNSBiA&list=UUhwKlOVR041tngjerWxVccw

CleanUpTimerTask.java

import java.util.TimerTask;

public class CleanUpTimerTask extends TimerTask
{
    public void run()
    {
        System.out.println("Clean up files...");
    }
}

TimerDemo.java

import java.util.Timer;
import java.util.TimerTask;

public class TimerDemo
{
    public static void main(String[] args) throws InterruptedException
    {
        TimerTask cleanUpTimerTask = new CleanUpTimerTask();
        Timer timer = new Timer();

        timer.scheduleAtFixedRate(cleanUpTimerTask, 3000, 1000);
        System.out.println("Timer has schedule the cleanUpTimerTask...");

        Thread.sleep(5000);

        System.out.println("Going to cancel...");
        timer.cancel();

        /*
         * Removes all cancelled tasks from this timer's task queue.
         * Calling this method has no effect on the behavior of the
         * timer, but eliminates the references to the cancelled tasks
         * from the queue. If there are no external references to
         * these tasks, they become eligible for garbage collection.
         *
         * Most programs will have no need to call this method. It is
         * designed for use by the rare application that cancels a
         * large number of tasks.
         *
         * Returns:
         *
         * the number of tasks removed from the queue.
         */

        System.out.println("purge value :" + timer.purge());
    }

}

Output:

Timer has schedule the cleanUpTimerTask...
Clean up files...
Clean up files...
Clean up files...
Going to cancel...
purge value :0

Click the below link to download the code:
https://sites.google.com/site/javaspringram2019/java_spring_2019/TimerDemo_purge.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java_Spring_2019/tree/master/Java_2019/TimerDemo_purge

Bitbucket Link:
https://bitbucket.org/ramram43210/java_spring_2019/src/2db5cd1f4e7d5ab55ad7af886d6164700143c614/Java_2019/TimerDemo_purge/?at=master

See also:
  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Spring Tutorial
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Cooking Tutorial
  • No comments:

    Post a Comment