-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathtimingwheel_test.go
91 lines (76 loc) · 2.08 KB
/
timingwheel_test.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
80
81
82
83
84
85
86
87
88
89
90
91
package timingwheel_test
import (
"testing"
"time"
"github.com/RussellLuo/timingwheel"
)
func TestTimingWheel_AfterFunc(t *testing.T) {
tw := timingwheel.NewTimingWheel(time.Millisecond, 20)
tw.Start()
defer tw.Stop()
durations := []time.Duration{
1 * time.Millisecond,
5 * time.Millisecond,
10 * time.Millisecond,
50 * time.Millisecond,
100 * time.Millisecond,
500 * time.Millisecond,
1 * time.Second,
}
for _, d := range durations {
t.Run("", func(t *testing.T) {
exitC := make(chan time.Time)
start := time.Now().UTC()
tw.AfterFunc(d, func() {
exitC <- time.Now().UTC()
})
got := (<-exitC).Truncate(time.Millisecond)
min := start.Add(d).Truncate(time.Millisecond)
err := 5 * time.Millisecond
if got.Before(min) || got.After(min.Add(err)) {
t.Errorf("Timer(%s) expiration: want [%s, %s], got %s", d, min, min.Add(err), got)
}
})
}
}
type scheduler struct {
intervals []time.Duration
current int
}
func (s *scheduler) Next(prev time.Time) time.Time {
if s.current >= len(s.intervals) {
return time.Time{}
}
next := prev.Add(s.intervals[s.current])
s.current += 1
return next
}
func TestTimingWheel_ScheduleFunc(t *testing.T) {
tw := timingwheel.NewTimingWheel(time.Millisecond, 20)
tw.Start()
defer tw.Stop()
s := &scheduler{intervals: []time.Duration{
1 * time.Millisecond, // start + 1ms
4 * time.Millisecond, // start + 5ms
5 * time.Millisecond, // start + 10ms
40 * time.Millisecond, // start + 50ms
50 * time.Millisecond, // start + 100ms
400 * time.Millisecond, // start + 500ms
500 * time.Millisecond, // start + 1s
}}
exitC := make(chan time.Time, len(s.intervals))
start := time.Now().UTC()
tw.ScheduleFunc(s, func() {
exitC <- time.Now().UTC()
})
accum := time.Duration(0)
for _, d := range s.intervals {
got := (<-exitC).Truncate(time.Millisecond)
accum += d
min := start.Add(accum).Truncate(time.Millisecond)
err := 5 * time.Millisecond
if got.Before(min) || got.After(min.Add(err)) {
t.Errorf("Timer(%s) expiration: want [%s, %s], got %s", accum, min, min.Add(err), got)
}
}
}