/
time_utils.go
72 lines (59 loc) · 1.18 KB
/
time_utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package utils
import (
"sync"
"time"
"go.uber.org/atomic"
)
type CancellableTimer struct {
isRunning *atomic.Bool
stopMutex sync.Mutex
timer *time.Timer
stop chan struct{}
stopped chan struct{}
C chan struct{}
}
func NewCancellableTimer() *CancellableTimer {
return &CancellableTimer{
isRunning: atomic.NewBool(false),
stop: make(chan struct{}),
stopped: make(chan struct{}),
C: make(chan struct{}),
}
}
func (t *CancellableTimer) Start(d time.Duration) {
t.isRunning.Store(true)
t.timer = time.NewTimer(d)
go func() {
select {
case <-t.stop:
if !t.timer.Stop() {
<-t.timer.C
}
t.isRunning.Store(false)
t.stopped <- struct{}{}
return
case <-t.timer.C:
t.isRunning.Store(false)
t.C <- struct{}{}
return
}
}()
return
}
// Stop can be called many times. Works on already stopeed timer.
func (t *CancellableTimer) Stop() {
t.stopMutex.Lock()
defer t.stopMutex.Unlock()
if !t.isRunning.Load() {
return
}
t.stop <- struct{}{}
<-t.stopped
}
///////////////////////////
func TimeUNIXMillis(t time.Time) int64 {
return t.UnixNano() / (1000 * 1000)
}
func TimePtr(t time.Time) *time.Time {
return &t
}