java - 可重置的 Java 计时器

标签 java timer

我想在 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 the ScheduledThreadPoolExecutor which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for the Timer/TimerTask combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassing TimerTask (just implement Runnable). Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer.

关于java - 可重置的 Java 计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32001/

相关文章:

java - 使用继承定义 nxn 矩阵

java - 为什么 lambda 强制我使用单个元素数组而不是最终对象?

黑莓 - 如何使时钟倒计时并显示在屏幕上

java - EJB3 计时器是否继承到创建它们的 bean?

java - 如何从包含多个帧的 .png 中制作 gif?

java DSP合成器奇怪的行为

c - Linux 内核延迟,低于 jiffies,没有忙等待

linux - 什么时候使用 gethrvtime() 代替 gethrtime() 更合适

multithreading - TTimer.OnTimer是否会使工作线程与主线程同步?

java - 从数组中拆分字符串的 double 值创建一个集合