-
Notifications
You must be signed in to change notification settings - Fork 10
/
time.go
53 lines (45 loc) · 1.21 KB
/
time.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
package utils
import (
"sync"
"sync/atomic"
"time"
)
var (
timestampTimer sync.Once
timestamp uint32
stopChan chan struct{}
)
// Timestamp returns the current time.
// Make sure to start the updater once using StartTimeStampUpdater() before calling.
func Timestamp() uint32 {
return atomic.LoadUint32(×tamp)
}
// StartTimeStampUpdater starts a concurrent function which stores the timestamp to an atomic value per second,
// which is much better for performance than determining it at runtime each time
func StartTimeStampUpdater() {
timestampTimer.Do(func() {
atomic.StoreUint32(×tamp, uint32(time.Now().Unix()))
c := make(chan struct{})
stopChan = c
go func(localChan chan struct{}, sleep time.Duration) {
ticker := time.NewTicker(sleep)
defer ticker.Stop()
for {
select {
case t := <-ticker.C:
atomic.StoreUint32(×tamp, uint32(t.Unix()))
case <-localChan:
return
}
}
}(c, 1*time.Second)
})
}
// StopTimeStampUpdater stops the timestamp updater
// WARNING: Make sure to call this function before the program exits, otherwise it will leak goroutines
func StopTimeStampUpdater() {
if stopChan != nil {
close(stopChan)
stopChan = nil
}
}