How to stop the task scheduled in java.util.Timer class

How to stop the task scheduled in java.util.Timer class

In Java, you can stop a task scheduled with the java.util.Timer class by canceling the corresponding TimerTask. Here's how you can do it:

  1. Schedule a task using the Timer.schedule(TimerTask task, long delay) method, which returns a reference to the scheduled TimerTask.

  2. To stop the task, call the cancel() method on the TimerTask reference.

Here's an example:

import java.util.Timer; import java.util.TimerTask; public class TimerExample { public static void main(String[] args) { Timer timer = new Timer(); // Schedule a task to run after 3 seconds TimerTask task = new TimerTask() { @Override public void run() { System.out.println("Task executed."); } }; // Schedule the task and get a reference to it timer.schedule(task, 3000); // 3000 milliseconds (3 seconds) // After some time, cancel the task try { Thread.sleep(2000); // Sleep for 2 seconds task.cancel(); // Cancel the task } catch (InterruptedException e) { e.printStackTrace(); } // Close the timer timer.cancel(); } } 

In this example:

  1. We create a Timer and schedule a TimerTask to run after 3 seconds.

  2. We then sleep for 2 seconds using Thread.sleep() and cancel the task using task.cancel().

  3. Finally, we cancel the timer using timer.cancel().

Keep in mind that once you cancel a TimerTask, it cannot be scheduled for execution again. If you need to reschedule the task, you would need to create a new instance of the TimerTask and schedule it.


More Tags

openid-connect typescript-typings interop robospice netflix-feign ienumerable countif stm32f1 onbackpressed computational-geometry

More Java Questions

More Geometry Calculators

More Date and Time Calculators

More Various Measurements Units Calculators

More Electrochemistry Calculators