cron.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. func (c *Cron) runWithRecovery(j Job) {
  128. defer func() {
  129. if r := recover(); r != nil {
  130. const size = 64 << 10
  131. buf := make([]byte, size)
  132. buf = buf[:runtime.Stack(buf, false)]
  133. c.logf("cron: panic running job: %v\n%s", r, buf)
  134. }
  135. }()
  136. j.Run()
  137. }
  138. // Run the scheduler.. this is private just due to the need to synchronize
  139. // access to the 'running' state variable.
  140. func (c *Cron) run() {
  141. // Figure out the next activation times for each entry.
  142. now := time.Now().In(c.location)
  143. for _, entry := range c.entries {
  144. entry.Next = entry.Schedule.Next(now)
  145. }
  146. for {
  147. // Determine the next entry to run.
  148. sort.Sort(byTime(c.entries))
  149. var effective time.Time
  150. if len(c.entries) == 0 || c.entries[0].Next.IsZero() {
  151. // If there are no entries yet, just sleep - it still handles new entries
  152. // and stop requests.
  153. effective = now.AddDate(10, 0, 0)
  154. } else {
  155. effective = c.entries[0].Next
  156. }
  157. timer := time.NewTimer(effective.Sub(now))
  158. select {
  159. case now = <-timer.C:
  160. // Run every entry whose next time was this effective time.
  161. for _, e := range c.entries {
  162. if e.Next != effective {
  163. break
  164. }
  165. go c.runWithRecovery(e.Job)
  166. e.Prev = e.Next
  167. e.Next = e.Schedule.Next(now)
  168. }
  169. continue
  170. case newEntry := <-c.add:
  171. c.entries = append(c.entries, newEntry)
  172. newEntry.Next = newEntry.Schedule.Next(time.Now().In(c.location))
  173. case <-c.snapshot:
  174. c.snapshot <- c.entrySnapshot()
  175. case <-c.stop:
  176. timer.Stop()
  177. return
  178. }
  179. // 'now' should be updated after newEntry and snapshot cases.
  180. now = time.Now().In(c.location)
  181. timer.Stop()
  182. }
  183. }
  184. // Logs an error to stderr or to the configured error log
  185. func (c *Cron) logf(format string, args ...interface{}) {
  186. if c.ErrorLog != nil {
  187. c.ErrorLog.Printf(format, args...)
  188. } else {
  189. log.Printf(format, args...)
  190. }
  191. }
  192. // Stop stops the cron scheduler if it is running; otherwise it does nothing.
  193. func (c *Cron) Stop() {
  194. if !c.running {
  195. return
  196. }
  197. c.stop <- struct{}{}
  198. c.running = false
  199. }
  200. // entrySnapshot returns a copy of the current cron entry list.
  201. func (c *Cron) entrySnapshot() []*Entry {
  202. entries := []*Entry{}
  203. for _, e := range c.entries {
  204. entries = append(entries, &Entry{
  205. Schedule: e.Schedule,
  206. Next: e.Next,
  207. Prev: e.Prev,
  208. Job: e.Job,
  209. })
  210. }
  211. return entries
  212. }