What should Timertask.scheduleAtFixedRate do if the clock changes?

后端 未结 2 761
滥情空心
滥情空心 2020-12-03 16:17

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

So we have

timer.scheduleAtFixedRate(task, delay, interval);

Mostly, this works fin

2条回答
  •  囚心锁ツ
    2020-12-03 16:54

    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.

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

    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().

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

    This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time [emphasis mine].

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

    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.

    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.

提交回复
热议问题