cron.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // This library implements a cron spec parser and runner. See the README for
  2. // more details.
  3. package cron
  4. import (
  5. "sort"
  6. "time"
  7. )
  8. // Cron keeps track of any number of entries, invoking the associated func as
  9. // specified by the spec. See http://en.wikipedia.org/wiki/Cron
  10. // It may be started and stopped.
  11. type Cron struct {
  12. Entries []*Entry
  13. stop chan struct{}
  14. add chan *Entry
  15. }
  16. // A cron entry consists of a schedule and the func to execute on that schedule.
  17. type Entry struct {
  18. *Schedule
  19. Next time.Time
  20. Func func()
  21. }
  22. type byTime []*Entry
  23. func (s byTime) Len() int { return len(s) }
  24. func (s byTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  25. func (s byTime) Less(i, j int) bool { return s[i].Next.Before(s[j].Next) }
  26. func New() *Cron {
  27. return &Cron{
  28. Entries: nil,
  29. add: make(chan *Entry, 1),
  30. stop: make(chan struct{}, 1),
  31. }
  32. }
  33. func (c *Cron) Add(spec string, cmd func()) {
  34. entry := &Entry{Parse(spec), time.Time{}, cmd}
  35. select {
  36. case c.add <- entry:
  37. // The run loop accepted the entry, nothing more to do.
  38. return
  39. default:
  40. // No one listening to that channel, so just add to the array.
  41. c.Entries = append(c.Entries, entry)
  42. }
  43. }
  44. func (c *Cron) Start() {
  45. go c.Run()
  46. }
  47. func (c *Cron) Run() {
  48. // Figure out the next activation times for each entry.
  49. now := time.Now()
  50. for _, entry := range c.Entries {
  51. entry.Next = entry.Schedule.Next(now)
  52. }
  53. for {
  54. // Determine the next entry to run.
  55. sort.Sort(byTime(c.Entries))
  56. var effective time.Time
  57. if len(c.Entries) == 0 {
  58. // If there are no entries yet, just sleep - it still handles new entries
  59. // and stop requests.
  60. effective = now.AddDate(10, 0, 0)
  61. } else {
  62. effective = c.Entries[0].Next
  63. }
  64. select {
  65. case now = <-time.After(effective.Sub(now)):
  66. // Run every entry whose next time was this effective time.
  67. for _, e := range c.Entries {
  68. if e.Next != effective {
  69. break
  70. }
  71. go e.Func()
  72. e.Next = e.Schedule.Next(effective)
  73. }
  74. case newEntry := <-c.add:
  75. c.Entries = append(c.Entries, newEntry)
  76. case <-c.stop:
  77. return
  78. }
  79. }
  80. }
  81. func (c Cron) Stop() {
  82. c.stop <- struct{}{}
  83. }