Custom dynamic clock in Java

大兔子大兔子 提交于 2019-12-13 03:15:56

问题


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));

}

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.

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!


回答1:


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);

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



来源:https://stackoverflow.com/questions/57708597/custom-dynamic-clock-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!