-
Notifications
You must be signed in to change notification settings - Fork 200
/
task.go
52 lines (43 loc) · 986 Bytes
/
task.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
package task
import "time"
type StopFn func()
// ticker is an interface which allows us to test RunTaskRepeateadly without
// needing to rely on actual timing which is not perfectly accurate and thus
// makes tests flakey.
type ticker interface {
stop()
tickChan() <-chan time.Time
}
func NewDefaultTicker(period time.Duration) *DefaultTicker {
return &DefaultTicker{*time.NewTicker(period)}
}
// DefaultTicker is an implementation of ticker which simply delegates to
// time.Ticker.
type DefaultTicker struct {
t time.Ticker
}
func (d *DefaultTicker) tickChan() <-chan time.Time {
return d.t.C
}
func (d *DefaultTicker) stop() {
d.t.Stop()
}
func RunTaskRepeateadly(task func(), t ticker) StopFn {
// Setup the ticker and the channel to signal
// the ending of the interval
stop := make(chan struct{})
go func() {
for {
select {
case <-t.tickChan():
task()
case <-stop:
t.stop()
return
}
}
}()
return func() {
stop <- struct{}{}
}
}