This repository was archived by the owner on Oct 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathticker.go
More file actions
67 lines (56 loc) · 1.31 KB
/
ticker.go
File metadata and controls
67 lines (56 loc) · 1.31 KB
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
package clock
import (
"time"
)
type mockTicker struct {
c chan time.Time
stop chan bool
clock Clock
interval time.Duration
start time.Time
}
var _ Ticker = new(mockTicker)
// note: this probably does not function the same way as the time.Timer
// in the event that the clock skips more than the timer interval. I've
// not yet dug deep into the runtimeTimer to see how that works.
// PRs are appreciated!
func (m *mockTicker) wait(ready chan<- struct{}) {
for i := time.Duration(1); true; i++ {
delta := m.start.Add(m.interval * i).Sub(m.clock.Now())
afterChan := m.clock.After(delta)
if i == time.Duration(1) {
ready <- struct{}{}
}
select {
case <-m.stop:
return
case <-afterChan:
select {
case m.c <- m.clock.Now():
case <-m.stop:
return
}
}
}
}
func (m *mockTicker) Chan() <-chan time.Time {
return m.c
}
func (m *mockTicker) Stop() {
m.stop <- true
}
// NewMockTicker creates a new Ticker using the provided Clock. You should not use this
// directly outside of unit tests; use Clock.NewTicker().
func NewMockTicker(c Clock, interval time.Duration) Ticker {
t := &mockTicker{
c: make(chan time.Time),
stop: make(chan bool),
interval: interval,
start: c.Now(),
clock: c,
}
ready := make(chan struct{})
go t.wait(ready)
<-ready
return t
}