-
Notifications
You must be signed in to change notification settings - Fork 0
/
repeater.go
79 lines (63 loc) · 1.14 KB
/
repeater.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
67
68
69
70
71
72
73
74
75
76
77
78
79
// Copyright (C) 2019-2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package timer
import (
"sync"
"time"
)
type Repeater struct {
handler func()
timeout chan struct{}
lock sync.Mutex
wg sync.WaitGroup
finished bool
frequency time.Duration
}
func NewRepeater(handler func(), frequency time.Duration) *Repeater {
repeater := &Repeater{
handler: handler,
timeout: make(chan struct{}, 1),
frequency: frequency,
}
repeater.wg.Add(1)
return repeater
}
func (r *Repeater) Stop() {
r.lock.Lock()
if !r.finished {
defer r.wg.Wait()
}
defer r.lock.Unlock()
r.finished = true
r.reset()
}
func (r *Repeater) Dispatch() {
r.lock.Lock()
defer r.lock.Unlock()
defer r.wg.Done()
timer := time.NewTimer(r.frequency)
cleared := false
for !r.finished {
r.lock.Unlock()
cleared = false
select {
case <-r.timeout:
case <-timer.C:
cleared = true
}
if !timer.Stop() && !cleared {
<-timer.C
}
if cleared {
r.handler()
}
timer.Reset(r.frequency)
r.lock.Lock()
}
}
func (r *Repeater) reset() {
select {
case r.timeout <- struct{}{}:
default:
}
}