forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathticker.go
77 lines (63 loc) · 1.18 KB
/
ticker.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
package timex
import (
"errors"
"time"
"github.com/tal-tech/go-zero/core/lang"
)
type (
// Ticker interface wraps the Chan and Stop methods.
Ticker interface {
Chan() <-chan time.Time
Stop()
}
// FakeTicker interface is used for unit testing.
FakeTicker interface {
Ticker
Done()
Tick()
Wait(d time.Duration) error
}
fakeTicker struct {
c chan time.Time
done chan lang.PlaceholderType
}
realTicker struct {
*time.Ticker
}
)
// NewTicker returns a Ticker.
func NewTicker(d time.Duration) Ticker {
return &realTicker{
Ticker: time.NewTicker(d),
}
}
func (rt *realTicker) Chan() <-chan time.Time {
return rt.C
}
// NewFakeTicker returns a FakeTicker.
func NewFakeTicker() FakeTicker {
return &fakeTicker{
c: make(chan time.Time, 1),
done: make(chan lang.PlaceholderType, 1),
}
}
func (ft *fakeTicker) Chan() <-chan time.Time {
return ft.c
}
func (ft *fakeTicker) Done() {
ft.done <- lang.Placeholder
}
func (ft *fakeTicker) Stop() {
close(ft.c)
}
func (ft *fakeTicker) Tick() {
ft.c <- Time()
}
func (ft *fakeTicker) Wait(d time.Duration) error {
select {
case <-time.After(d):
return errors.New("timeout")
case <-ft.done:
return nil
}
}