24

I am trying to make a simple timer that plays a beep after the specified number of seconds. I managed to get it to work, but the TimerTask continues to run after the beep. Now do I stop execution? Here is my code:

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;

        Timer timer = new Timer();

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

        timer.schedule(task, delay);
    }
}
Zim
  • 590
  • 1
  • 4
  • 10
  • I am sorry. I figured this out really fast right after posting. I had to declare timer as final and call timer.cancel() after the beep inside the run() method. Not sure that it's a great solution to call a local variables method from within an inner class though... – Zim Apr 19 '13 at 09:07

4 Answers4

55

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;
    }
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Erik Pragt
  • 13,513
  • 11
  • 58
  • 64
  • Copied from here http://stackoverflow.com/questions/1409116/how-to-stop-the-task-scheduled-in-java-util-timer-class – Suresh Atta Apr 19 '13 at 09:04
  • I tried this, it didn't work. How is run ever going to change to false in your example? I just called timer.cancel() directly after the beep and it worked. – Zim Apr 19 '13 at 09:13
  • We'll, that depends on you of course. You could keep at timer, like in the link of Baadshah, or use some other condition. When do you want to stop the beeping? – Erik Pragt Apr 19 '13 at 09:17
  • I just want one beep and then continue executing whatever code is next. In my case - just stop the program after the beep. – Zim Apr 19 '13 at 09:21
  • 1
    Then why do you use a TimerTask? Why not just use: 'Toolkit.getDefaultToolkit().beep() directly? – Erik Pragt Apr 19 '13 at 09:51
  • Because then it wouldn't be a timer, would it? – Zim Apr 19 '13 at 11:31
  • 7
    please note that calling .cancel() kills the Timer (thus the "scheduling" part) and not any running TimerTask. it kills future Tasks, but not the currently running one ("Terminates this timer, discarding any currently scheduled tasks. Does not interfere with a currently executing task (if it exists).") in the current example, no one cares cause it is just a proof of concept, but still needs mentioning – Belun Mar 29 '16 at 16:38
  • As a note calling `purge` should rarely be necessary, unless you need to free those for garbage collection "immediately" while keeping a reference to the Timer itself...just as a note. – rogerdpack Jul 25 '16 at 18:22
6

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);
    }
}
Zim
  • 590
  • 1
  • 4
  • 10
1

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

Sean Landsman
  • 7,033
  • 2
  • 29
  • 33
0

isStart = true; // if true timmer function countiue called , else time canceled
Timer timer = new Timer(); timer.schedule(new TimerClass(), 0, 5000);

class TimerClass extends TimerTask {
    
    public void run() {
        
        if (isStart) {
           yourFunction();
        }else {
            cancel();
        }

    }
}
patel jigar
  • 52
  • 1
  • 7