|
@@ -0,0 +1,41 @@
|
|
1
|
+package com.xhkjedu.utils;
|
|
2
|
+
|
|
3
|
+import java.util.concurrent.Executors;
|
|
4
|
+import java.util.concurrent.ScheduledExecutorService;
|
|
5
|
+import java.util.concurrent.TimeUnit;
|
|
6
|
+import java.util.concurrent.atomic.AtomicLong;
|
|
7
|
+
|
|
8
|
+/**
|
|
9
|
+ * @author ywx
|
|
10
|
+ * @classname SystemClock
|
|
11
|
+ * @description todo
|
|
12
|
+ * @date 2022/11/9 20:31
|
|
13
|
+ **/
|
|
14
|
+public class SystemClock {
|
|
15
|
+ private static final SystemClock MILLIS_CLOCK = new SystemClock(1);
|
|
16
|
+ private final long precision;
|
|
17
|
+ private final AtomicLong now;
|
|
18
|
+
|
|
19
|
+ private SystemClock(long precision) {
|
|
20
|
+ this.precision = precision;
|
|
21
|
+ now = new AtomicLong(System.currentTimeMillis());
|
|
22
|
+ scheduleClockUpdating();
|
|
23
|
+ }
|
|
24
|
+
|
|
25
|
+ public static SystemClock millisClock() {
|
|
26
|
+ return MILLIS_CLOCK;
|
|
27
|
+ }
|
|
28
|
+
|
|
29
|
+ private void scheduleClockUpdating() {
|
|
30
|
+ ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(runnable -> {
|
|
31
|
+ Thread thread = new Thread(runnable, "system.clock");
|
|
32
|
+ thread.setDaemon(true);
|
|
33
|
+ return thread;
|
|
34
|
+ });
|
|
35
|
+ scheduler.scheduleAtFixedRate(() -> now.set(System.currentTimeMillis()), precision, precision, TimeUnit.MILLISECONDS);
|
|
36
|
+ }
|
|
37
|
+
|
|
38
|
+ public long now() {
|
|
39
|
+ return now.get();
|
|
40
|
+ }
|
|
41
|
+}
|