问题描述
我想要一个每2秒更改一次自己的私有变量的类.我知道如果我做
I want to have a class that changes its own private variables every 2 seconds. I know that if I do something like
import java.util.Timer;
//...
Timer timer;
//...
timer.schedule(new ChangeSomething(), 2000);
它将在2秒后执行 ChangeSomething()
,是否有办法告诉它每2秒执行一次操作,或者,如果我将其放入 ChangeSomething()
It will execute ChangeSomething()
after 2 seconds, is there a way to tell it to do something every 2 seconds, or, If I put inside ChangeSomething()
timer.schedule(new ChangeSomething(), 2000);
能行吗?
在旁注中, timer.cancel()
到底能做什么?
On a side-note, what does timer.cancel()
exactly do?
推荐答案
使用 timer.scheduleAtFixedRate()
将其安排为每两秒重复一次:
Use timer.scheduleAtFixedRate()
to schedule it to recur every two seconds:
从Javadoc中获取 Timer.cancel()
:
From the javadoc for Timer.cancel()
:
与一次执行单个任务的 Timer
的内部执行线程有关:
Relating to internal execution thread for a Timer
that executes a single task once:
这篇关于在Java中创建重复计时器提醒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!