简体   繁体   中英

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?

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM