How to stop a timer in java

拟墨画扇 提交于 2019-12-12 16:52:52

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/33726952/how-to-stop-a-timer-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!