How to stop a running TimerTask

You need to cancel the timer by calling the following methods

timer.cancel();  // Terminates this timer, discarding any currently scheduled tasks.
timer.purge();   // Removes all cancelled tasks from this timer's task queue.

This will cancel the task, so something like this would work:

import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.Toolkit;

class Alarm {

    private static boolean run = true;

    public static void main(String[] args) {
        long delay;
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a delay in seconds: ");
        delay = scan.nextInt()*1000;

        final Timer timer = new Timer();

        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if(run) {
                   Toolkit.getDefaultToolkit().beep();
                } else {
                   timer.cancel();
                   timer.purge();
                }
            }
        };

        timer.schedule(task, delay);

        // set run to false here to stop the timer.
        run = false;
    }
}

Here is what worked for me (used the purge() suggestion also):

import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.Toolkit;

class Alarm {

    public static void main(String[] args) {
        long delay;
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a delay in seconds: ");
        delay = scan.nextInt()*1000;

        final Timer timer = new Timer();

        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                Toolkit.getDefaultToolkit().beep();
                timer.cancel();
                timer.purge();
            }
        };

        timer.schedule(task, delay);
    }
}

cancel() should do it - cancel stops the cancels the given TimerTask / Timer

Tags:

Timer

Java