periodic.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package task
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. // Periodic is a task that runs periodically.
  7. type Periodic struct {
  8. // Interval of the task being run
  9. Interval time.Duration
  10. // Execute is the task function
  11. Execute func() error
  12. access sync.Mutex
  13. timer *time.Timer
  14. running bool
  15. }
  16. func (t *Periodic) hasClosed() bool {
  17. t.access.Lock()
  18. defer t.access.Unlock()
  19. return !t.running
  20. }
  21. func (t *Periodic) checkedExecute() error {
  22. if t.hasClosed() {
  23. return nil
  24. }
  25. if err := t.Execute(); err != nil {
  26. t.access.Lock()
  27. t.running = false
  28. t.access.Unlock()
  29. return err
  30. }
  31. t.access.Lock()
  32. defer t.access.Unlock()
  33. if !t.running {
  34. return nil
  35. }
  36. t.timer = time.AfterFunc(t.Interval, func() {
  37. t.checkedExecute() // nolint: errcheck
  38. })
  39. return nil
  40. }
  41. // Start implements common.Runnable.
  42. func (t *Periodic) Start() error {
  43. t.access.Lock()
  44. if t.running {
  45. return nil
  46. }
  47. t.running = true
  48. t.access.Unlock()
  49. if err := t.checkedExecute(); err != nil {
  50. t.access.Lock()
  51. t.running = false
  52. t.access.Unlock()
  53. return err
  54. }
  55. return nil
  56. }
  57. // Close implements common.Closable.
  58. func (t *Periodic) Close() error {
  59. t.access.Lock()
  60. defer t.access.Unlock()
  61. t.running = false
  62. if t.timer != nil {
  63. t.timer.Stop()
  64. t.timer = nil
  65. }
  66. return nil
  67. }