Search code examples
javatimer

How to fix error to do with timer in Java?


I'm trying to write a timer that will count down from 10 and then stop when it gets to 0 but in the 'timer.cancel();' part at the bottom of the code, there is a red line underneath 'timer'. It says that I haven't defined 'timer'. I did define 'timer' earlier on in the code so I'm not sure what I'm doing wrong?

(I am doing this in NetBeans 8.2)

package javaapplication3;
import java.util.Timer;
import java.util.TimerTask;

public class JavaApplication3 {
     public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new timeInterval(), 0, 1000);
    }
}

class timeInterval extends TimerTask {

    int countdown = 10;

    public void run() {
        countdown = countdown - 1;
        System.out.println(countdown);
        if (countdown <= 0) {
            timer.cancel();
    }

}
}

Solution

  • This is a scope problem. You can't refer to the named object timer in the class TimerTask because it has no knowledge of it.

    Possibly check out this article on scope of variables

    you can try just calling the cancel() function. You can read about the TimerTask java class here

    if (countdown <= 0) {
      cancel();
    }
    

    You should also get in the habit of making your class variables private, unless you have a good reason not to.

    Note this will not kill the Timer object, only the task scheduled for it. If you don't plan on using it again, you should add some code in to cancel it.