cron.go 5.8 KB

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