【发布时间】:2020-01-02 15:17:33
【问题描述】:
我正在尝试在 java 中创建一个自定义时钟。在应用程序初始化时,时钟将设置为系统时间并正常滴答作响。但它也应该能够从自定义时间开始计时。
public class DockerClock {
static Clock clock = Clock.tickMillis(TimeZone.getDefault().toZoneId());
static Instant instant = Instant.now(clock);
static Instant prev = instant;
public Clock getClock() {
return this.clock;
}
public Instant getInstant() {
return instant;
}
public void setTime() {
instant = Instant.now(this.clock).plusSeconds(10);
Clock newClock = Clock.fixed(instant, TimeZone.getDefault().toZoneId());
this.clock = Clock.offset(newClock, Duration.ofMinutes(5));
}
但我面临的问题是,在调用 setTime 方法时,时钟在那个瞬间是固定的(而且是正确的)。
这里的理想方法应该是什么?最后,我想要做的只是一个工作时钟,它能够通过我提供的偏移量向前/向后漂移,并像时钟一样继续滴答作响。
更新:在执行Clock.offset(baseClock, Duration...) 之后,我能够根据我传递给它的偏移量来使时钟前后移动。但是,在程序运行时,如果我更改系统时间,我实现的时钟开始根据系统时钟显示时间,即从更改的系统时间重新开始。
有什么可能的方法可以完全取消它与我的系统时钟的链接吗?我只想在开始时将它与系统公鸡同步,以后再也不同步了!
【问题讨论】:
-
如果您希望它继续滴答作响,那么您不希望
Clock.fixed“总是返回相同的瞬间”。 (docs.oracle.com/javase/8/docs/api/java/time/…) 而不是Clock.offset(newClock尝试Clock.offset(this.clock -
难道你不能只在内部正常运行一个时钟,并在需要获取当前
Instant时定义一个添加到当前时间的偏移量吗?这基本上就是您从`Clock.offset(...)` 获得的OffsetClock实例正在做的事情(无法更改偏移量) -
提示,不要使用
TimeZone.getDefault().toZoneId(),只需使用ZoneId.systemDefault()。不要涉及设计不佳且早已过时的TimeZone类。 -
谢谢@racraman。你的建议有帮助。请参阅原始问题的更新部分。