Showing posts with label TimerTask. Show all posts
Showing posts with label TimerTask. Show all posts

Wednesday, 6 February 2019

How to Cancel the timer task using cancel() method of TimerTask?

🚀 Enjoying these Java tutorials? Click here to Subscribe to Ram N Java and never miss an update!

Introduction to Cancelling Tasks in Java

In Java, the TimerTask class is incredibly useful for scheduling code to run at a specific time or repeatedly. However, there are many situations where you need to stop a task before it finishes its scheduled runs. This is where the cancel() method comes into play.

What is the cancel() Method?

The cancel() method is a part of the TimerTask class. When you call this method on a task, it ensures that the task will never run again. If the task was scheduled for one-time execution and hasn't run yet, it is cancelled. If it was a repeated task, all future executions are stopped.

Step-by-Step Implementation

To use this in your code, you typically follow these steps:

  • Create a Class: Define a class that extends TimerTask and override the run() method.
  • Initialize Timer: Create a Timer object to schedule your task.
  • Call Cancel: Use the cancel() method on your task object when your specific condition is met.

Why Use Task Cancellation?

Memory management and performance are key! By cancelling tasks that are no longer needed, you prevent your application from wasting resources on background processes that don't contribute to the final result.

More Java Tutorials from Ram N Java

If you found this helpful, check out these other related videos from my channel:



ReminderTimerTask.java

import java.util.TimerTask;

public class ReminderTimerTask extends TimerTask
{
    public void run()
    {
        System.out.println("Wake up...");
    }
}

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...");

        Thread.sleep(10000);
        /*
         * 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 = reminderTimerTask.cancel();
        System.out.println(value);

    }

}

Output:

Timer has schedule the reminderTimerTask...
Wake up...
Wake up...
Wake up...
true

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

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java_spring_2019/src/7a570b442b7e7cac6e2bc811d1d0cc686cb3a5c1/Java_2019/TimerDemo_timetask_cancel_V1/?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
  • How to create a new timer whose associated thread has the specified name

    🚀 Master Java with Ram N Java!

    Join thousands of learners and level up your coding skills today.

    SUBSCRIBE NOW

    Introduction to Naming Your Timer Thread

    In Java, when you use the Timer class to schedule background tasks, a separate thread is created to handle those tasks. By default, Java gives these threads generic names like "Timer-0". While this works fine for execution, it makes debugging a nightmare!

    Why Should You Use a Custom Thread Name?

    Imagine you have five different timers running in your application. If one of them crashes or causes a performance bottleneck, your logs will just show "Timer-1". Which one is that?

    • Easier Debugging: Identify exactly which background task is running.
    • Better Logging: Custom names appear in your console and log files.
    • Professional Code: It's a best practice in multi-threaded programming.

    How to Set the Name (Simple Code)

    The Timer class provides a specific constructor that allows you to pass a String as the name of the thread. Here is how you can do it:

    Timer myTimer = new Timer("MyEmailSchedulerThread");

    Now, whenever this timer executes a TimerTask, the thread handling it will be clearly labeled as "MyEmailSchedulerThread".

    Explore More Java Tutorials

    If you enjoyed this tutorial, check out these related videos from the channel:



    ReminderTimerTask.java

    import java.util.TimerTask;

    public class ReminderTimerTask extends TimerTask
    {
        public void run()
        {
            System.out.println("Wake up...");
        }
    }

    TimerDemo.java

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

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

            /*
             *
             * Creates a new timer whose associated thread has the
             * specified name. The associated thread does not run as a
             * daemon.
             *
             * Parameters:
             *
             * name - the name of the associated thread
             */

            Timer timer = new Timer("Reminder 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...
    Wake up...
    Wake up...
    Wake up...
    Wake up...
    Wake up...
    Wake up...

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

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

    Bitbucket Link:
    https://bitbucket.org/ramram43210/java_spring_2019/src/2db5cd1f4e7d5ab55ad7af886d6164700143c614/Java_2019/TimerDemo_thread_name/?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
  • Tutorials