-
Notifications
You must be signed in to change notification settings - Fork 10
/
time.go
36 lines (31 loc) · 884 Bytes
/
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
package utils
import (
"sync"
"sync/atomic"
"time"
)
var (
timestampTimer sync.Once
timestamp uint32
)
// 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() {
// set initial value
atomic.StoreUint32(×tamp, uint32(time.Now().Unix()))
go func(sleep time.Duration) {
ticker := time.NewTicker(sleep)
defer ticker.Stop()
for t := range ticker.C {
// update timestamp
atomic.StoreUint32(×tamp, uint32(t.Unix()))
}
}(1 * time.Second) // duration
})
}