【问题标题】:Custom dynamic clock in JavaJava中的自定义动态时钟
【发布时间】: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。你的建议有帮助。请参阅原始问题的更新部分。

标签: java time clock


【解决方案1】:

你可以这样安排你的工作:

ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        // TODO update your clock to current time.
    }
}, 0, 1, TimeUnit.SECONDS);

您可以根据您的要求安排此线程每 1 秒或每分钟运行一次。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-18
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
  • 1970-01-01
相关资源
最近更新 更多