/
cancellable_timer.go
61 lines (52 loc) · 1.09 KB
/
cancellable_timer.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
package run
import (
"sync/atomic"
"time"
"github.com/form3tech-oss/f1/internal/trace"
)
type CancellableTimer struct {
cancel chan bool
timer *time.Timer
C chan bool
reset chan time.Duration
cancelled int32
}
func NewCancellableTimer(d time.Duration) *CancellableTimer {
timer := &CancellableTimer{
cancel: make(chan bool),
C: make(chan bool),
reset: make(chan time.Duration),
timer: time.NewTimer(d),
}
go timer.wait()
return timer
}
// internal wait goroutine wrapping time.After
func (c *CancellableTimer) wait() {
for {
select {
case d := <-c.reset:
c.timer.Reset(d)
case <-c.timer.C:
c.C <- true
return
case <-c.cancel:
trace.ReceivedFromChannel("cancel")
c.C <- false
trace.SentToChannel("C")
return
}
}
}
// Cancel makes all the waiters receive false
func (c *CancellableTimer) Cancel() bool {
trace.Event("Closing Channel 'cancel'")
if atomic.CompareAndSwapInt32(&c.cancelled, 0, 1) {
close(c.cancel)
return true
}
return false
}
func (c *CancellableTimer) Reset(duration time.Duration) {
c.reset <- duration
}