Java自定义动态时钟 [英] Custom dynamic clock in Java

查看:218
本文介绍了Java自定义动态时钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Java中创建自定义时钟。在应用程序初始化时,时钟将设置为系统时间,并且将正常计时。但是它也应该具有从自定义时间开始计时的功能。

I am trying to create a custom clock in java. On the application initialization, the clock will be set to the system time and will tick normally. But it should also have the capability to start ticking from a custom time.

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时方法中,时钟在那一刻是固定的(也是正确的)。

But the problem I am facing is that on calling the setTime method, the clock is fixed (and rightly so) at that very instant.

这里理想的方法是什么?最后,我要制作的是一个工作时钟,它能够按我提供的偏移量向前/向后漂移,并像时钟一样继续滴答。

What should be the ideal approach here? In the end all I want to make is a working clock with ability to drift forward/backward with an offset I provide and continue ticking like a clock.

更新:在执行 Clock.offset(baseClock,Duration ...)之后,我可以根据传递给我的偏移量使时钟来回移动它。但是,在程序运行时,如果更改系统时间,则我实现的时钟会根据系统时钟开始显示时间,即从更改后的系统时间重新开始。

UPDATE: after doing Clock.offset(baseClock, Duration...), I am able to make the clock go back and forward according to the offset I pass to it. However, while the program is running, if I change the system time, my implemented clock starts showing time according to the system clock, ie it starts again from the changed system time.

有什么办法可以将它与系统时钟完全取消链接?我只想在开始时将其与系统时钟进行同步,而永远不会再同步!

Is there any possible way I can de-link it with my system clock altogether? I want to sync it with the system cock only in the starting and never again!

推荐答案

您可以像这样安排工作:

You can schedule your job like this:

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

您可以根据需要将线程安排为每1秒或每分钟运行一次。

You can schedule this thread to run every 1 second or minute depending on your requirement.

这篇关于Java自定义动态时钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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