如果时钟发生变化,Timertask.scheduleAtFixedRate应该怎么做? [英] What should Timertask.scheduleAtFixedRate do if the clock changes?

查看:439
本文介绍了如果时钟发生变化,Timertask.scheduleAtFixedRate应该怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们希望每1000秒运行一次任务(比方说)。

We want to run a task every 1000 seconds (say).

所以我们有

timer.scheduleAtFixedRate(task, delay, interval);

大多数情况下,这样做很好。但是,这是一个嵌入式系统,用户可以更改实时时钟。如果他们在我们设置定时器之后将其设置为过去的时间,则计时器似乎直到原始实时日期/时间才执行。因此,如果他们将其设置为3天,则计时器不会执行3天:(

Mostly, this works fine. However, this is an embedded system and the user can change the real time clock. If they set it to a time in the past after we set up the timer, it seems the timer doesn't execute until the original real-time date/time. So if they set it back 3 days, the timer doesn't execute for 3 days :(

这是允许的行为,还是Java库中的缺陷?Oracle javadocs似乎没有提及有关系统时钟的基础值的依赖性。

Is this permissible behaviour, or a defect in the Java library? The Oracle javadocs don't seem to mention anything about the dependency or not on the underlying value of the system clock.

如果允许,我们如何发现这个时钟更改并重新安排我们的计时器?

If it's permissible, how do we spot this clock change and reschedule our timers?

推荐答案

查看Java 1.7的计时器的来源,它似乎是使用 System.currentTimeMillis()来确定任务的下一次执行。

Looking at the source of Timer for Java 1.7, it appears that is uses System.currentTimeMillis() to determine the next execution of a task.

但是,查看 ScheduledThreadPoolExecutor 的来源,它使用 System.nanoTime()

However, looking at the source of ScheduledThreadPoolExecutor, it uses System.nanoTime().

这意味着如果你使用一个代替 Timer ,你将不会看到这种行为。要创建一个,例如,使用 Executors.newScheduledThreadPool()

Which means you won't see that behaviour if you use one in place of a Timer. To create one, use, for instance, Executors.newScheduledThreadPool().

为什么你不会看到这种行为是因为什么的文档System.nanoTime()说:

Why you wouldn't see this behaviour is because of what the doc for System.nanoTime() says:


此方法只能是用于测量经过的时间,与系统或挂钟时间的任何其他概念无关。 返回的值表示纳秒,因为某些固定但任意的原始时间 [强调我的]。

关于是否这是计时器中的错误,可能......

As to whether this is a bug in Timer, maybe...

请注意,与 ScheduledExecutorService不同计时器支持绝对时间,也许这解释了它使用 System.currentTimeMillis();此外,计时器自Java 1.3以来一直存在,而 System.nanoTime()仅出现在1.5中。

Note that unlike a ScheduledExecutorService, a Timer supports absolute time, and maybe this explains its use of System.currentTimeMillis(); also, Timer has been there since Java 1.3 while System.nanoTime() only appears in 1.5.

但使用 System.currentTimeMillis()的结果是计时器对系统日期/时间敏感...而javadoc中没有记录。

But a consequence of using System.currentTimeMillis() is that Timer is sensitive to the system date/time... And that is not documented in the javadoc.

这篇关于如果时钟发生变化,Timertask.scheduleAtFixedRate应该怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆