简体   繁体   English

如何在Java中停止计时器

[英]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. 每当有人输入内容时,方法run()都会不断被调用,因此计时器会不断被调用,但是这不会停止以前的计时器,我希望计时器停止运行,然后重新调用自身,这样就不会出现问题。 Anyone know a way? 有人知道吗?

The TimerTask class has a method called cancel() which you can call to cancel a pending timer. TimerTask类具有一个名为cancel()的方法,您可以调用该方法来取消挂起的计时器。

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() . 在代码中,您可能需要修改timer()函数以返回对新创建的TimerTask对象的引用,以便以后可以调用cancel()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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