我想在 java.utils.Timer 中有一个可重置时间的 java.utils.Timer。我需要设置一个一次性事件以在 X 秒内发生。如果在创建计时器和 X 秒之间没有发生任何事情,则事件正常发生。
但是,如果在 X 秒过去之前,我决定事件应该在 Y 秒之后发生,那么我希望能够告诉计时器重置其时间,以便事件在 Y 秒内发生。 例如。计时器应该能够执行以下操作:
Timer timer = new Timer();
timer.schedule(timerTask, 5000); //Timer starts in 5000 ms (X)
//At some point between 0 and 5000 ms...
setNewTime(timer, 8000); //timerTask will fire in 8000ms from NOW (Y).
我看不到使用 utils 计时器执行此操作的方法,就好像您调用 cancel() 您无法再次安排它一样。
我接近复制此行为的唯一方法是使用 javax.swing.Timer 并涉及停止原始计时器并创建一个新计时器。即:
timer.stop();
timer = new Timer(8000, ActionListener);
timer.start();
有没有更简单的方法??
最佳答案
根据Timer
文档,从 Java 1.5 开始,您应该更喜欢 ScheduledThreadPoolExecutor
反而。 (为了便于使用,您可能希望使用 Executors
.newSingleThreadScheduledExecutor()
创建这个执行器;它创建的东西很像 Timer
。)
很酷的是,当您安排任务时(通过调用 schedule()
),它会返回 ScheduledFuture
目的。您可以使用它来取消计划任务。然后,您可以自由地提交具有不同触发时间的新任务。
ETA:链接到的 Timer
文档没有说明任何关于 ScheduledThreadPoolExecutor
的内容,但是 OpenJDK版本是这样说的:
Java 5.0 introduced the
java.util.concurrent
package and one of the concurrency utilities therein is theScheduledThreadPoolExecutor
which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for theTimer
/TimerTask
combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassingTimerTask
(just implementRunnable
). ConfiguringScheduledThreadPoolExecutor
with one thread makes it equivalent toTimer
.
关于java - 可重置的 Java 计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32001/