cron.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. }
  15. // A cron entry consists of a schedule and the func to execute on that schedule.
  16. type Entry struct {
  17. *Schedule
  18. Next time.Time
  19. Func func()
  20. }
  21. type byTime []*Entry
  22. func (s byTime) Len() int { return len(s) }
  23. func (s byTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  24. func (s byTime) Less(i, j int) bool { return s[i].Next.Before(s[j].Next) }
  25. func New() *Cron {
  26. return &Cron{
  27. Entries: nil,
  28. stop: make(chan struct{}),
  29. }
  30. }
  31. func (c *Cron) Add(spec string, cmd func()) {
  32. c.Entries = append(c.Entries, &Entry{Parse(spec), time.Time{}, cmd})
  33. }
  34. // func (c *Cron) Run() {
  35. // if len(c.Entries) == 0 {
  36. // return
  37. // }
  38. // var (
  39. // now = time.Now()
  40. // effective = now
  41. // )
  42. // // Figure out the next activation times for each entry.
  43. // for _, entry := range c.Entries {
  44. // entry.Next = entry.Schedule.Next(now)
  45. // }
  46. // sort.Sort(byTime(c.Entries))
  47. // for {
  48. // // Sleep until the next job needs to get run.
  49. // effective = c.Entries[0].Next
  50. // time.Sleep(effective.Sub(now))
  51. // now = time.Now()
  52. // // Run every entry whose next time was this effective time.
  53. // // Find how long until the next entry needs to get run.
  54. // for _, e := range c.Entries {
  55. // if e.Next != effective {
  56. // break
  57. // }
  58. // // TODO: Check that it's at least one
  59. // go c.Func()
  60. // }
  61. // case <-c.stop:
  62. // return
  63. // }
  64. // }
  65. // }
  66. func (c Cron) Stop() {
  67. c.stop <- struct{}{}
  68. }