问题
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