periodic.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. // OnFailure will be called when Execute returns non-nil error
  13. OnError func(error)
  14. access sync.RWMutex
  15. timer *time.Timer
  16. closed bool
  17. }
  18. func (t *Periodic) setClosed(f bool) {
  19. t.access.Lock()
  20. t.closed = f
  21. t.access.Unlock()
  22. }
  23. func (t *Periodic) hasClosed() bool {
  24. t.access.RLock()
  25. defer t.access.RUnlock()
  26. return t.closed
  27. }
  28. func (t *Periodic) checkedExecute() error {
  29. if t.hasClosed() {
  30. return nil
  31. }
  32. if err := t.Execute(); err != nil {
  33. return err
  34. }
  35. t.access.Lock()
  36. t.timer = time.AfterFunc(t.Interval, func() {
  37. if err := t.checkedExecute(); err != nil && t.OnError != nil {
  38. t.OnError(err)
  39. }
  40. })
  41. t.access.Unlock()
  42. return nil
  43. }
  44. // Start implements common.Runnable. Start must not be called multiple times without Close being called.
  45. func (t *Periodic) Start() error {
  46. t.setClosed(false)
  47. if err := t.checkedExecute(); err != nil {
  48. t.setClosed(true)
  49. return err
  50. }
  51. return nil
  52. }
  53. // Close implements common.Closable.
  54. func (t *Periodic) Close() error {
  55. t.access.Lock()
  56. defer t.access.Unlock()
  57. t.closed = true
  58. if t.timer != nil {
  59. t.timer.Stop()
  60. t.timer = nil
  61. }
  62. return nil
  63. }