cron.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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.
  63. func New() *Cron {
  64. return &Cron{
  65. entries: nil,
  66. add: make(chan *Entry),
  67. stop: make(chan struct{}),
  68. snapshot: make(chan []*Entry),
  69. running: false,
  70. ErrorLog: nil,
  71. location: time.Now().Location(),
  72. }
  73. }
  74. // A wrapper that turns a func() into a cron.Job
  75. type FuncJob func()
  76. func (f FuncJob) Run() { f() }
  77. // AddFunc adds a func to the Cron to be run on the given schedule.
  78. func (c *Cron) AddFunc(spec string, cmd func()) error {
  79. return c.AddJob(spec, FuncJob(cmd))
  80. }
  81. // AddJob adds a Job to the Cron to be run on the given schedule.
  82. func (c *Cron) AddJob(spec string, cmd Job) error {
  83. schedule, err := Parse(spec)
  84. if err != nil {
  85. return err
  86. }
  87. c.Schedule(schedule, cmd)
  88. return nil
  89. }
  90. // Schedule adds a Job to the Cron to be run on the given schedule.
  91. func (c *Cron) Schedule(schedule Schedule, cmd Job) {
  92. entry := &Entry{
  93. Schedule: schedule,
  94. Job: cmd,
  95. }
  96. if !c.running {
  97. c.entries = append(c.entries, entry)
  98. return
  99. }
  100. c.add <- entry
  101. }
  102. // Entries returns a snapshot of the cron entries.
  103. func (c *Cron) Entries() []*Entry {
  104. if c.running {
  105. c.snapshot <- nil
  106. x := <-c.snapshot
  107. return x
  108. }
  109. return c.entrySnapshot()
  110. }
  111. // SetLocations sets the time zone location
  112. func (c *Cron) SetLocation(location *time.Location) {
  113. c.location = location
  114. }
  115. // Start the cron scheduler in its own go-routine.
  116. func (c *Cron) Start() {
  117. c.running = true
  118. go c.run()
  119. }
  120. func (c *Cron) runWithRecovery(j Job) {
  121. defer func() {
  122. if r := recover(); r != nil {
  123. const size = 64 << 10
  124. buf := make([]byte, size)
  125. buf = buf[:runtime.Stack(buf, false)]
  126. c.logf("cron: panic running job: %v\n%s", r, buf)
  127. }
  128. }()
  129. j.Run()
  130. }
  131. // Run the scheduler.. this is private just due to the need to synchronize
  132. // access to the 'running' state variable.
  133. func (c *Cron) run() {
  134. // Figure out the next activation times for each entry.
  135. now := time.Now().In(c.location)
  136. for _, entry := range c.entries {
  137. entry.Next = entry.Schedule.Next(now)
  138. }
  139. for {
  140. // Determine the next entry to run.
  141. sort.Sort(byTime(c.entries))
  142. var effective time.Time
  143. if len(c.entries) == 0 || c.entries[0].Next.IsZero() {
  144. // If there are no entries yet, just sleep - it still handles new entries
  145. // and stop requests.
  146. effective = now.AddDate(10, 0, 0)
  147. } else {
  148. effective = c.entries[0].Next
  149. }
  150. select {
  151. case now = <-time.After(effective.Sub(now)):
  152. // Run every entry whose next time was this effective time.
  153. for _, e := range c.entries {
  154. if e.Next != effective {
  155. break
  156. }
  157. go c.runWithRecovery(e.Job)
  158. e.Prev = e.Next
  159. e.Next = e.Schedule.Next(now)
  160. }
  161. continue
  162. case newEntry := <-c.add:
  163. c.entries = append(c.entries, newEntry)
  164. newEntry.Next = newEntry.Schedule.Next(time.Now().Local())
  165. case <-c.snapshot:
  166. c.snapshot <- c.entrySnapshot()
  167. case <-c.stop:
  168. return
  169. }
  170. // 'now' should be updated after newEntry and snapshot cases.
  171. now = time.Now().Local()
  172. }
  173. }
  174. // Logs an error to stderr or to the configured error log
  175. func (c *Cron) logf(format string, args ...interface{}) {
  176. if c.ErrorLog != nil {
  177. c.ErrorLog.Printf(format, args...)
  178. } else {
  179. log.Printf(format, args...)
  180. }
  181. }
  182. // Stop stops the cron scheduler if it is running; otherwise it does nothing.
  183. func (c *Cron) Stop() {
  184. if !c.running {
  185. return
  186. }
  187. c.stop <- struct{}{}
  188. c.running = false
  189. }
  190. // entrySnapshot returns a copy of the current cron entry list.
  191. func (c *Cron) entrySnapshot() []*Entry {
  192. entries := []*Entry{}
  193. for _, e := range c.entries {
  194. entries = append(entries, &Entry{
  195. Schedule: e.Schedule,
  196. Next: e.Next,
  197. Prev: e.Prev,
  198. Job: e.Job,
  199. })
  200. }
  201. return entries
  202. }