cron.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. // Figure out the next activation times for each entry.
  46. now := time.Now()
  47. for _, entry := range c.Entries {
  48. entry.Next = entry.Schedule.Next(now)
  49. }
  50. for {
  51. // Determine the next entry to run.
  52. sort.Sort(byTime(c.Entries))
  53. var effective time.Time
  54. if len(c.Entries) == 0 {
  55. // If there are no entries yet, just sleep - it still handles new entries
  56. // and stop requests.
  57. effective = now.AddDate(10, 0, 0)
  58. } else {
  59. effective = c.Entries[0].Next
  60. }
  61. select {
  62. case now = <-time.After(effective.Sub(now)):
  63. // Run every entry whose next time was this effective time.
  64. for _, e := range c.Entries {
  65. if e.Next != effective {
  66. break
  67. }
  68. go e.Func()
  69. e.Next = e.Schedule.Next(effective)
  70. }
  71. case newEntry := <-c.add:
  72. c.Entries = append(c.Entries, newEntry)
  73. case <-c.stop:
  74. return
  75. }
  76. }
  77. }
  78. func (c Cron) Stop() {
  79. c.stop <- struct{}{}
  80. }