cron.go 5.8 KB

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