ticker.go 1.2 KB

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