cron.go 5.2 KB

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