cron.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. Description string
  34. Spec string
  35. // The schedule on which this job should be run.
  36. Schedule Schedule
  37. // The next time the job will run. This is the zero time if Cron has not been
  38. // started or this entry's schedule is unsatisfiable
  39. Next time.Time
  40. // The last time this job was run. This is the zero time if the job has never
  41. // been run.
  42. Prev time.Time
  43. // The Job to run.
  44. Job Job
  45. ExecTimes int // Execute times count.
  46. }
  47. // byTime is a wrapper for sorting the entry array by time
  48. // (with zero time at the end).
  49. type byTime []*Entry
  50. func (s byTime) Len() int { return len(s) }
  51. func (s byTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  52. func (s byTime) Less(i, j int) bool {
  53. // Two zero times should return false.
  54. // Otherwise, zero is "greater" than any other time.
  55. // (To sort it at the end of the list.)
  56. if s[i].Next.IsZero() {
  57. return false
  58. }
  59. if s[j].Next.IsZero() {
  60. return true
  61. }
  62. return s[i].Next.Before(s[j].Next)
  63. }
  64. // New returns a new Cron job runner.
  65. func New() *Cron {
  66. return &Cron{
  67. entries: nil,
  68. add: make(chan *Entry),
  69. stop: make(chan struct{}),
  70. snapshot: make(chan []*Entry),
  71. running: false,
  72. ErrorLog: nil,
  73. }
  74. }
  75. // A wrapper that turns a func() into a cron.Job
  76. type FuncJob func()
  77. func (f FuncJob) Run() { f() }
  78. // AddFunc adds a func to the Cron to be run on the given schedule.
  79. func (c *Cron) AddFunc(desc, spec string, cmd func()) (*Entry, error) {
  80. return c.AddJob(desc, spec, FuncJob(cmd))
  81. }
  82. // AddJob adds a Job to the Cron to be run on the given schedule.
  83. func (c *Cron) AddJob(desc, spec string, cmd Job) (*Entry, error) {
  84. schedule, err := Parse(spec)
  85. if err != nil {
  86. return nil, err
  87. }
  88. return c.Schedule(desc, spec, schedule, cmd), nil
  89. }
  90. // Schedule adds a Job to the Cron to be run on the given schedule.
  91. func (c *Cron) Schedule(desc, spec string, schedule Schedule, cmd Job) *Entry {
  92. entry := &Entry{
  93. Description: desc,
  94. Spec: spec,
  95. Schedule: schedule,
  96. Job: cmd,
  97. }
  98. if c.running {
  99. c.add <- entry
  100. } else {
  101. c.entries = append(c.entries, entry)
  102. }
  103. return entry
  104. }
  105. // Entries returns a snapshot of the cron entries.
  106. func (c *Cron) Entries() []*Entry {
  107. if c.running {
  108. c.snapshot <- nil
  109. x := <-c.snapshot
  110. return x
  111. }
  112. return c.entrySnapshot()
  113. }
  114. // Start the cron scheduler in its own go-routine, or no-op if already started.
  115. func (c *Cron) Start() {
  116. if c.running {
  117. return
  118. }
  119. c.running = true
  120. go c.run()
  121. }
  122. func (c *Cron) runWithRecovery(j Job) {
  123. defer func() {
  124. if r := recover(); r != nil {
  125. const size = 64 << 10
  126. buf := make([]byte, size)
  127. buf = buf[:runtime.Stack(buf, false)]
  128. c.logf("cron: panic running job: %v\n%s", r, buf)
  129. }
  130. }()
  131. j.Run()
  132. }
  133. // Run the scheduler.. this is private just due to the need to synchronize
  134. // access to the 'running' state variable.
  135. func (c *Cron) run() {
  136. // Figure out the next activation times for each entry.
  137. now := time.Now().Local()
  138. for _, entry := range c.entries {
  139. entry.Next = entry.Schedule.Next(now)
  140. }
  141. for {
  142. // Determine the next entry to run.
  143. sort.Sort(byTime(c.entries))
  144. var effective time.Time
  145. if len(c.entries) == 0 || c.entries[0].Next.IsZero() {
  146. // If there are no entries yet, just sleep - it still handles new entries
  147. // and stop requests.
  148. effective = now.AddDate(10, 0, 0)
  149. } else {
  150. effective = c.entries[0].Next
  151. }
  152. timer := time.NewTimer(effective.Sub(now))
  153. select {
  154. case now = <-timer.C:
  155. // Run every entry whose next time was this effective time.
  156. for _, e := range c.entries {
  157. if e.Next != effective {
  158. break
  159. }
  160. go c.runWithRecovery(e.Job)
  161. e.ExecTimes++
  162. e.Prev = e.Next
  163. e.Next = e.Schedule.Next(now)
  164. }
  165. continue
  166. case newEntry := <-c.add:
  167. c.entries = append(c.entries, newEntry)
  168. newEntry.Next = newEntry.Schedule.Next(time.Now().Local())
  169. case <-c.snapshot:
  170. c.snapshot <- c.entrySnapshot()
  171. case <-c.stop:
  172. timer.Stop()
  173. return
  174. }
  175. // 'now' should be updated after newEntry and snapshot cases.
  176. now = time.Now().Local()
  177. timer.Stop()
  178. }
  179. }
  180. // Logs an error to stderr or to the configured error log
  181. func (c *Cron) logf(format string, args ...interface{}) {
  182. if c.ErrorLog != nil {
  183. c.ErrorLog.Printf(format, args...)
  184. } else {
  185. log.Printf(format, args...)
  186. }
  187. }
  188. // Stop stops the cron scheduler if it is running; otherwise it does nothing.
  189. func (c *Cron) Stop() {
  190. if !c.running {
  191. return
  192. }
  193. c.stop <- struct{}{}
  194. c.running = false
  195. }
  196. // entrySnapshot returns a copy of the current cron entry list.
  197. func (c *Cron) entrySnapshot() []*Entry {
  198. entries := []*Entry{}
  199. for _, e := range c.entries {
  200. entries = append(entries, &Entry{
  201. Description: e.Description,
  202. Spec: e.Spec,
  203. Schedule: e.Schedule,
  204. Next: e.Next,
  205. Prev: e.Prev,
  206. Job: e.Job,
  207. ExecTimes: e.ExecTimes,
  208. })
  209. }
  210. return entries
  211. }