cron.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. // This library implements a cron spec parser and runner. See the README for
  2. // more details.
  3. package cron
  4. import (
  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. }
  18. // Job is an interface for submitted cron jobs.
  19. type Job interface {
  20. Run()
  21. }
  22. // The Schedule describes a job's duty cycle.
  23. type Schedule interface {
  24. // Return the next activation time, later than the given time.
  25. // Next is invoked initially, and then each time the job is run.
  26. Next(time.Time) time.Time
  27. }
  28. // Entry consists of a schedule and the func to execute on that schedule.
  29. type Entry struct {
  30. // The schedule on which this job should be run.
  31. Schedule Schedule
  32. // The next time the job will run. This is the zero time if Cron has not been
  33. // started or this entry's schedule is unsatisfiable
  34. Next time.Time
  35. // The last time this job was run. This is the zero time if the job has never
  36. // been run.
  37. Prev time.Time
  38. // The Job to run.
  39. Job Job
  40. }
  41. // byTime is a wrapper for sorting the entry array by time
  42. // (with zero time at the end).
  43. type byTime []*Entry
  44. func (s byTime) Len() int { return len(s) }
  45. func (s byTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  46. func (s byTime) Less(i, j int) bool {
  47. // Two zero times should return false.
  48. // Otherwise, zero is "greater" than any other time.
  49. // (To sort it at the end of the list.)
  50. if s[i].Next.IsZero() {
  51. return false
  52. }
  53. if s[j].Next.IsZero() {
  54. return true
  55. }
  56. return s[i].Next.Before(s[j].Next)
  57. }
  58. // New returns a new Cron job runner.
  59. func New() *Cron {
  60. return &Cron{
  61. entries: nil,
  62. add: make(chan *Entry),
  63. stop: make(chan struct{}),
  64. snapshot: make(chan []*Entry),
  65. running: false,
  66. }
  67. }
  68. // A wrapper that turns a func() into a cron.Job
  69. type FuncJob func()
  70. func (f FuncJob) Run() { f() }
  71. // AddFunc adds a func to the Cron to be run on the given schedule.
  72. func (c *Cron) AddFunc(spec string, cmd func()) error {
  73. return c.AddJob(spec, FuncJob(cmd))
  74. }
  75. // AddFunc adds a Job to the Cron to be run on the given schedule.
  76. func (c *Cron) AddJob(spec string, cmd Job) error {
  77. schedule, err := Parse(spec)
  78. if err != nil {
  79. return err
  80. }
  81. c.Schedule(schedule, cmd)
  82. return nil
  83. }
  84. // Schedule adds a Job to the Cron to be run on the given schedule.
  85. func (c *Cron) Schedule(schedule Schedule, cmd Job) {
  86. entry := &Entry{
  87. Schedule: schedule,
  88. Job: cmd,
  89. }
  90. if !c.running {
  91. c.entries = append(c.entries, entry)
  92. return
  93. }
  94. c.add <- entry
  95. }
  96. // Entries returns a snapshot of the cron entries.
  97. func (c *Cron) Entries() []*Entry {
  98. if c.running {
  99. c.snapshot <- nil
  100. x := <-c.snapshot
  101. return x
  102. }
  103. return c.entrySnapshot()
  104. }
  105. // Start the cron scheduler in its own go-routine.
  106. func (c *Cron) Start() {
  107. c.running = true
  108. go c.run()
  109. }
  110. // Run the scheduler.. this is private just due to the need to synchronize
  111. // access to the 'running' state variable.
  112. func (c *Cron) run() {
  113. // Figure out the next activation times for each entry.
  114. now := time.Now().Local()
  115. for _, entry := range c.entries {
  116. entry.Next = entry.Schedule.Next(now)
  117. }
  118. for {
  119. // Determine the next entry to run.
  120. sort.Sort(byTime(c.entries))
  121. var effective time.Time
  122. if len(c.entries) == 0 || c.entries[0].Next.IsZero() {
  123. // If there are no entries yet, just sleep - it still handles new entries
  124. // and stop requests.
  125. effective = now.AddDate(10, 0, 0)
  126. } else {
  127. effective = c.entries[0].Next
  128. }
  129. select {
  130. case now = <-time.After(effective.Sub(now)):
  131. // Run every entry whose next time was this effective time.
  132. for _, e := range c.entries {
  133. if e.Next != effective {
  134. break
  135. }
  136. go e.Job.Run()
  137. e.Prev = e.Next
  138. e.Next = e.Schedule.Next(effective)
  139. }
  140. continue
  141. case newEntry := <-c.add:
  142. c.entries = append(c.entries, newEntry)
  143. newEntry.Next = newEntry.Schedule.Next(now)
  144. case <-c.snapshot:
  145. c.snapshot <- c.entrySnapshot()
  146. case <-c.stop:
  147. return
  148. }
  149. // 'now' should be updated after newEntry and snapshot cases.
  150. now = time.Now().Local()
  151. }
  152. }
  153. // Stop the cron scheduler.
  154. func (c *Cron) Stop() {
  155. c.stop <- struct{}{}
  156. c.running = false
  157. }
  158. // entrySnapshot returns a copy of the current cron entry list.
  159. func (c *Cron) entrySnapshot() []*Entry {
  160. entries := []*Entry{}
  161. for _, e := range c.entries {
  162. entries = append(entries, &Entry{
  163. Schedule: e.Schedule,
  164. Next: e.Next,
  165. Prev: e.Prev,
  166. Job: e.Job,
  167. })
  168. }
  169. return entries
  170. }