如何在java中停止计时器 [英] How to stop a timer in java
问题描述
我有一个名为 timer 的方法,每次用户输入内容时我都会运行该方法,并且计时器计划为一分钟,但是如果用户在不到一分钟的时间内输入内容,然后重新调用自己,我希望计时器取消整个过程过程再次发生.我的方法如下:
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:
输入法
public static String run(){
timer(); //runs everytime I call run()
String s = input.nextLine();
return s;
}
定时器方法
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);
}
方法 run() 每次有人输入内容时都会被调用,因此计时器会不断被调用,但这并不会停止之前的计时器,但我希望计时器停止,然后重新调用自身,以便不存在该问题.有人知道方法吗?
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?
推荐答案
TimerTask
类有一个方法叫做 cancel()
您可以调用它来取消挂起的计时器.
The TimerTask
class has a method called cancel()
which you can call to cancel a pending timer.
在您的代码中,您可能需要修改您的 timer()
函数以返回对新创建的 TimerTask
对象的引用,以便您以后可以调用 <代码>取消()代码>.
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()
.
这篇关于如何在java中停止计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!