-
Notifications
You must be signed in to change notification settings - Fork 0
/
gticker.go
47 lines (40 loc) · 807 Bytes
/
gticker.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
package gticker
import (
"sync/atomic"
"time"
)
type InstantTicker interface {
Stop()
Reset(d time.Duration)
C() <-chan time.Time
}
type instantTicker struct {
tic *time.Ticker
tch chan time.Time
instTicked int32
stopped int32
}
func NewInstantTicker(d time.Duration) InstantTicker {
return &instantTicker{
tic: time.NewTicker(d),
tch: make(chan time.Time, 1),
}
}
func (it *instantTicker) Stop() {
it.tic.Stop()
if atomic.CompareAndSwapInt32(&it.stopped, 0, 1) {
close(it.tch)
}
}
func (it *instantTicker) Reset(d time.Duration) {
it.tic.Reset(d)
}
func (it *instantTicker) C() <-chan time.Time {
if atomic.CompareAndSwapInt32(&it.instTicked, 0, 1) {
if atomic.LoadInt32(&it.stopped) != 1 {
it.tch <- time.Now()
return it.tch
}
}
return it.tic.C
}