ticker.go 1.0 KB

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