cron.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. // This library implements a cron spec parser and runner. See the README for
  2. // more details.
  3. package cron
  4. import (
  5. "fmt"
  6. "sort"
  7. "time"
  8. )
  9. // Cron keeps track of any number of entries, invoking the associated func as
  10. // specified by the schedule. It may be started, stopped, and the entries may
  11. // be inspected while running.
  12. type Cron struct {
  13. entries []*Entry
  14. stop chan struct{}
  15. add chan *Entry
  16. snapshot chan []*Entry
  17. running bool
  18. }
  19. // Job is an interface for submitted cron jobs.
  20. type Job interface {
  21. Run()
  22. }
  23. // The Schedule describes a job's duty cycle.
  24. type Schedule interface {
  25. // Return the next activation time, later than the given time.
  26. // Next is invoked initially, and then each time the job is run.
  27. Next(time.Time) time.Time
  28. }
  29. // Entry consists of a schedule and the func to execute on that schedule.
  30. type Entry struct {
  31. // The schedule on which this job should be run.
  32. Schedule Schedule
  33. // The next time the job will run. This is the zero time if Cron has not been
  34. // started or this entry's schedule is unsatisfiable
  35. Next time.Time
  36. // The last time this job was run. This is the zero time if the job has never
  37. // been run.
  38. Prev time.Time
  39. // The Job to run.
  40. Job Job
  41. }
  42. // byTime is a wrapper for sorting the entry array by time
  43. // (with zero time at the end).
  44. type byTime []*Entry
  45. func (s byTime) Len() int { return len(s) }
  46. func (s byTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  47. func (s byTime) Less(i, j int) bool {
  48. // Two zero times should return false.
  49. // Otherwise, zero is "greater" than any other time.
  50. // (To sort it at the end of the list.)
  51. if s[i].Next.IsZero() {
  52. return false
  53. }
  54. if s[j].Next.IsZero() {
  55. return true
  56. }
  57. return s[i].Next.Before(s[j].Next)
  58. }
  59. // New returns a new Cron job runner.
  60. func New() *Cron {
  61. return &Cron{
  62. entries: nil,
  63. add: make(chan *Entry),
  64. stop: make(chan struct{}),
  65. snapshot: make(chan []*Entry),
  66. running: false,
  67. }
  68. }
  69. // A wrapper that turns a func() into a cron.Job
  70. type FuncJob func()
  71. func (f FuncJob) Run() { f() }
  72. // AddFunc adds a func to the Cron to be run on the given schedule.
  73. func (c *Cron) AddFunc(spec string, cmd func()) error {
  74. return c.AddJob(spec, FuncJob(cmd))
  75. }
  76. // AddFunc adds a Job to the Cron to be run on the given schedule.
  77. func (c *Cron) AddJob(spec string, cmd Job) error {
  78. schedule, err := Parse(spec)
  79. if err != nil {
  80. return err
  81. }
  82. c.Schedule(schedule, cmd)
  83. return nil
  84. }
  85. // Schedule adds a Job to the Cron to be run on the given schedule.
  86. func (c *Cron) Schedule(schedule Schedule, cmd Job) {
  87. entry := &Entry{
  88. Schedule: schedule,
  89. Job: cmd,
  90. }
  91. if !c.running {
  92. c.entries = append(c.entries, entry)
  93. return
  94. }
  95. c.add <- entry
  96. }
  97. // Entries returns a snapshot of the cron entries.
  98. func (c *Cron) Entries() []*Entry {
  99. if c.running {
  100. c.snapshot <- nil
  101. x := <-c.snapshot
  102. return x
  103. }
  104. return c.entrySnapshot()
  105. }
  106. // Start the cron scheduler in its own go-routine.
  107. func (c *Cron) Start() {
  108. c.running = true
  109. go c.run()
  110. }
  111. func (c *Cron) runWithRecovery(j Job) {
  112. defer func() {
  113. if r := recover(); r != nil {
  114. fmt.Println("Cron function panicked: ", r)
  115. }
  116. }()
  117. j.Run()
  118. }
  119. // Run the scheduler.. this is private just due to the need to synchronize
  120. // access to the 'running' state variable.
  121. func (c *Cron) run() {
  122. // Figure out the next activation times for each entry.
  123. now := time.Now().Local()
  124. for _, entry := range c.entries {
  125. entry.Next = entry.Schedule.Next(now)
  126. }
  127. for {
  128. // Determine the next entry to run.
  129. sort.Sort(byTime(c.entries))
  130. var effective time.Time
  131. if len(c.entries) == 0 || c.entries[0].Next.IsZero() {
  132. // If there are no entries yet, just sleep - it still handles new entries
  133. // and stop requests.
  134. effective = now.AddDate(10, 0, 0)
  135. } else {
  136. effective = c.entries[0].Next
  137. }
  138. select {
  139. case now = <-time.After(effective.Sub(now)):
  140. // Run every entry whose next time was this effective time.
  141. for _, e := range c.entries {
  142. if e.Next != effective {
  143. break
  144. }
  145. go c.runWithRecovery(e.Job)
  146. e.Prev = e.Next
  147. e.Next = e.Schedule.Next(effective)
  148. }
  149. continue
  150. case newEntry := <-c.add:
  151. c.entries = append(c.entries, newEntry)
  152. newEntry.Next = newEntry.Schedule.Next(now)
  153. case <-c.snapshot:
  154. c.snapshot <- c.entrySnapshot()
  155. case <-c.stop:
  156. return
  157. }
  158. // 'now' should be updated after newEntry and snapshot cases.
  159. now = time.Now().Local()
  160. }
  161. }
  162. // Stop stops the cron scheduler if it is running; otherwise it does nothing.
  163. func (c *Cron) Stop() {
  164. if !c.running {
  165. return
  166. }
  167. c.stop <- struct{}{}
  168. c.running = false
  169. }
  170. // entrySnapshot returns a copy of the current cron entry list.
  171. func (c *Cron) entrySnapshot() []*Entry {
  172. entries := []*Entry{}
  173. for _, e := range c.entries {
  174. entries = append(entries, &Entry{
  175. Schedule: e.Schedule,
  176. Next: e.Next,
  177. Prev: e.Prev,
  178. Job: e.Job,
  179. })
  180. }
  181. return entries
  182. }