有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中的时间自定义动态时钟

我正在尝试用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...)之后,我能够使时钟根据我传递给它的偏移量来回移动。但是,当程序运行时,如果我更改系统时间,我的实现时钟将根据系统时钟开始显示时间,即它将从更改后的系统时间重新开始

是否有任何可能的方法可以将它与我的系统时钟完全断开?我只想在启动时将其与系统旋塞同步,而不再同步


共 (1) 个答案

  1. # 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秒或每分钟运行一次