forked from quickfixgo/quickfix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
event_timer.go
66 lines (52 loc) · 790 Bytes
/
event_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
62
63
64
65
66
package internal
import (
"sync"
"time"
)
type EventTimer struct {
f func()
timer *time.Timer
done chan struct{}
wg sync.WaitGroup
}
func NewEventTimer(task func()) *EventTimer {
t := &EventTimer{
f: task,
timer: newStoppedTimer(),
done: make(chan struct{}),
}
t.wg.Add(1)
go func() {
defer t.wg.Done()
for {
select {
case <-t.timer.C:
t.f()
case <-t.done:
t.timer.Stop()
return
}
}
}()
return t
}
func (t *EventTimer) Stop() {
if t == nil {
return
}
close(t.done)
t.wg.Wait()
}
func (t *EventTimer) Reset(timeout time.Duration) {
if t == nil {
return
}
t.timer.Reset(timeout)
}
func newStoppedTimer() *time.Timer {
timer := time.NewTimer(time.Second)
if !timer.Stop() {
<-timer.C
}
return timer
}