Thursday 7 February 2019

How to Cancel the timer task inside the run() method of TimerTask?


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

ReminderTimerTask.java

import java.util.TimerTask;

public class ReminderTimerTask extends TimerTask
{
    public void run()
    {
        System.out.println("Wake up...");
     
        /*
         * Cancels this timer task. If the task has been scheduled for
         * one-time execution and has not yet run, or has not yet been
         * scheduled, it will never run. If the task has been
         * scheduled for repeated execution, it will never run again.
         * (If the task is running when this call occurs, the task
         * will run to completion, but will never run again.)
         *
         * Returns:true if this task is scheduled for one-time
         * execution and has not yet run, or this task is scheduled
         * for repeated execution. Returns false if the task was
         * scheduled for one-time execution and has already run, or if
         * the task was never scheduled, or if the task was already
         * cancelled
         *
         */

        boolean value = cancel();
        System.out.println(value);
     
        System.out.println("ReminderTimerTask is cancelled");

    }
}

TimerDemo.java

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

public class TimerDemo
{
    public static void main(String[] args) throws InterruptedException
    {

        Timer timer = new Timer();
        TimerTask reminderTimerTask = new ReminderTimerTask();

        timer.schedule(reminderTimerTask, 5000, 2000);

        System.out.println("Timer has schedule the reminderTimerTask...");

    }

}

Output:

Timer has schedule the reminderTimerTask...
Wake up...
true
ReminderTimerTask is cancelled

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

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java_spring_2019/src/1ebed8b1986b12a20c2bf9302a0adc45079f1aad/Java_2019/TimerDemo_timetask_cancel_V2/?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