github.com/lingyao2333/mo-zero@v1.4.1/core/timex/ticker.go (about) 1 package timex 2 3 import ( 4 "errors" 5 "time" 6 7 "github.com/lingyao2333/mo-zero/core/lang" 8 ) 9 10 // errTimeout indicates a timeout. 11 var errTimeout = errors.New("timeout") 12 13 type ( 14 // Ticker interface wraps the Chan and Stop methods. 15 Ticker interface { 16 Chan() <-chan time.Time 17 Stop() 18 } 19 20 // FakeTicker interface is used for unit testing. 21 FakeTicker interface { 22 Ticker 23 Done() 24 Tick() 25 Wait(d time.Duration) error 26 } 27 28 fakeTicker struct { 29 c chan time.Time 30 done chan lang.PlaceholderType 31 } 32 33 realTicker struct { 34 *time.Ticker 35 } 36 ) 37 38 // NewTicker returns a Ticker. 39 func NewTicker(d time.Duration) Ticker { 40 return &realTicker{ 41 Ticker: time.NewTicker(d), 42 } 43 } 44 45 func (rt *realTicker) Chan() <-chan time.Time { 46 return rt.C 47 } 48 49 // NewFakeTicker returns a FakeTicker. 50 func NewFakeTicker() FakeTicker { 51 return &fakeTicker{ 52 c: make(chan time.Time, 1), 53 done: make(chan lang.PlaceholderType, 1), 54 } 55 } 56 57 func (ft *fakeTicker) Chan() <-chan time.Time { 58 return ft.c 59 } 60 61 func (ft *fakeTicker) Done() { 62 ft.done <- lang.Placeholder 63 } 64 65 func (ft *fakeTicker) Stop() { 66 close(ft.c) 67 } 68 69 func (ft *fakeTicker) Tick() { 70 ft.c <- time.Now() 71 } 72 73 func (ft *fakeTicker) Wait(d time.Duration) error { 74 select { 75 case <-time.After(d): 76 return errTimeout 77 case <-ft.done: 78 return nil 79 } 80 }