user3450498
user3450498

Reputation: 267

How to stop a timer in java

I have a method called timer that I run everytime a user inputs something and the timer is scheduled for a minute, but I want the timer to cancel if the user enters something in less than a minute and then recall itself so the whole process happens again. My methods are below:

Input method

public static String run(){ 
     timer(); //runs everytime I call run()
     String s = input.nextLine();
     return s;
}

Timer method

public static void timer() {
    TimerTask task = new TimerTask() {
        public void run() {
            System.out.println("Times up");
        }
    };
    long delay = TimeUnit.MINUTES.toMillis(1);
    Timer t = new Timer();
    t.schedule(task, delay);
}

method run() keeps getting called everytime someone inputs something so timer keeps getting called but that doesn't stop the previous timers though, I want the timer to stop, then recall itself so that problem doesn't exist. Anyone know a way?

Upvotes: 2

Views: 1625

Answers (1)

Greg Hewgill
Greg Hewgill

Reputation: 992717

The TimerTask class has a method called cancel() which you can call to cancel a pending timer.

In your code, you will probably need to modify your timer() function to return a reference to the newly created TimerTask object, so that you can later call cancel().

Upvotes: 4

Related Questions