现在,我的代码看起来像这样:
Timer timer = new javax.swing.Timer(5000, myActionEvent);
根据我所看到的(以及 Timer
类的 Javadocs),计时器将等待 5000 毫秒(5 秒),触发操作事件,等待 5000 毫秒,再次触发, 等等。然而,我试图获得的行为是启动计时器,触发事件,计时器等待 5000 毫秒,再次触发,然后等待,然后再次触发。
除非我错过了什么,否则我看不到一种方法来创建一个在触发之前不等待的计时器。有没有一个好的、干净的方法来模拟这个?
Right now, I have code that looks something like this:
Timer timer = new javax.swing.Timer(5000, myActionEvent);
According to what I'm seeing (and the Javadocs for the Timer
class), the timer will wait 5000 milliseconds (5 seconds), fire the action event, wait 5000 milliseconds, fire again, and so on. However, the behavior that I'm trying to obtain is that the timer is started, the event is fired, the timer waits 5000 milliseconds, fires again, then waits before firing again.
Unless I missed something, I don't see a way to create a timer that doesn't wait before firing. Is there a good, clean way to emulate this?
发布评论
评论(4)
您只能在构造函数中指定延迟。您需要更改初始延迟(触发第一个事件之前的时间)。您无法在构造函数中设置,但可以使用 setInitialDelay 方法。
如果您在第一次射击前不需要等待:
You can only specify the delay in the constructor. You need to change the initial delay (the time before firing the first event). You cannot set in the constuctor, but you can use the setInitialDelay method of the Timer class.
If you need no wait before the first firing:
我不确定这是否会有很大帮助,但是:
I am not sure if this will be of much help, but:
我根本不会使用计时器,而是使用
ScheduledExecutorService
请注意,有
scheduleAtFixedRate()
和scheduleWithFixedDelay()
其语义略有不同。阅读 JavaDoc 并找出您需要哪一个。I wouldn't use a Timer at all, but instead use a
ScheduledExecutorService
Please note that there is
scheduleAtFixedRate()
andscheduleWithFixedDelay()
which have slightly different semantics. Read the JavaDoc and find out which one you need.简单的解决方案:
但我喜欢计时器。
setInitialDelay
(0)
好多了。Simple solution:
But I like
timer.
setInitialDelay
(0)
a lot better.