cron.go 5.7 KB

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