You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

212 lines
5.0 KiB

10 years ago
  1. // Copyright 2012 Rob Figueiredo. All rights reserved.
  2. // Copyright 2014 The Gogs Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package cron
  6. import (
  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. }
  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. Description string
  33. Spec string
  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. ExecTimes int // Execute times count.
  45. }
  46. // byTime is a wrapper for sorting the entry array by time
  47. // (with zero time at the end).
  48. type byTime []*Entry
  49. func (s byTime) Len() int { return len(s) }
  50. func (s byTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  51. func (s byTime) Less(i, j int) bool {
  52. // Two zero times should return false.
  53. // Otherwise, zero is "greater" than any other time.
  54. // (To sort it at the end of the list.)
  55. if s[i].Next.IsZero() {
  56. return false
  57. }
  58. if s[j].Next.IsZero() {
  59. return true
  60. }
  61. return s[i].Next.Before(s[j].Next)
  62. }
  63. // New returns a new Cron job runner.
  64. func New() *Cron {
  65. return &Cron{
  66. entries: nil,
  67. add: make(chan *Entry),
  68. stop: make(chan struct{}),
  69. snapshot: make(chan []*Entry),
  70. running: false,
  71. }
  72. }
  73. // A wrapper that turns a func() into a cron.Job
  74. type FuncJob func()
  75. func (f FuncJob) Run() { f() }
  76. // AddFunc adds a func to the Cron to be run on the given schedule.
  77. func (c *Cron) AddFunc(desc, spec string, cmd func()) (*Entry, error) {
  78. return c.AddJob(desc, spec, FuncJob(cmd))
  79. }
  80. // AddFunc adds a Job to the Cron to be run on the given schedule.
  81. func (c *Cron) AddJob(desc, spec string, cmd Job) (*Entry, error) {
  82. schedule, err := Parse(spec)
  83. if err != nil {
  84. return nil, err
  85. }
  86. return c.Schedule(desc, spec, schedule, cmd), nil
  87. }
  88. // Schedule adds a Job to the Cron to be run on the given schedule.
  89. func (c *Cron) Schedule(desc, spec string, schedule Schedule, cmd Job) *Entry {
  90. entry := &Entry{
  91. Description: desc,
  92. Spec: spec,
  93. Schedule: schedule,
  94. Job: cmd,
  95. }
  96. if c.running {
  97. c.add <- entry
  98. } else {
  99. c.entries = append(c.entries, entry)
  100. }
  101. return entry
  102. }
  103. // Entries returns a snapshot of the cron entries.
  104. func (c *Cron) Entries() []*Entry {
  105. if c.running {
  106. c.snapshot <- nil
  107. x := <-c.snapshot
  108. return x
  109. }
  110. return c.entrySnapshot()
  111. }
  112. // Start the cron scheduler in its own go-routine.
  113. func (c *Cron) Start() {
  114. c.running = true
  115. go c.run()
  116. }
  117. // Run the scheduler.. this is private just due to the need to synchronize
  118. // access to the 'running' state variable.
  119. func (c *Cron) run() {
  120. // Figure out the next activation times for each entry.
  121. now := time.Now().Local()
  122. for _, entry := range c.entries {
  123. entry.Next = entry.Schedule.Next(now)
  124. }
  125. for {
  126. // Determine the next entry to run.
  127. sort.Sort(byTime(c.entries))
  128. var effective time.Time
  129. if len(c.entries) == 0 || c.entries[0].Next.IsZero() {
  130. // If there are no entries yet, just sleep - it still handles new entries
  131. // and stop requests.
  132. effective = now.AddDate(10, 0, 0)
  133. } else {
  134. effective = c.entries[0].Next
  135. }
  136. select {
  137. case now = <-time.After(effective.Sub(now)):
  138. // Run every entry whose next time was this effective time.
  139. for _, e := range c.entries {
  140. if e.Next != effective {
  141. break
  142. }
  143. go e.Job.Run()
  144. e.ExecTimes++
  145. e.Prev = e.Next
  146. e.Next = e.Schedule.Next(effective)
  147. }
  148. continue
  149. case newEntry := <-c.add:
  150. c.entries = append(c.entries, newEntry)
  151. newEntry.Next = newEntry.Schedule.Next(now)
  152. case <-c.snapshot:
  153. c.snapshot <- c.entrySnapshot()
  154. case <-c.stop:
  155. return
  156. }
  157. // 'now' should be updated after newEntry and snapshot cases.
  158. now = time.Now().Local()
  159. }
  160. }
  161. // Stop the cron scheduler.
  162. func (c *Cron) Stop() {
  163. c.stop <- struct{}{}
  164. c.running = false
  165. }
  166. // entrySnapshot returns a copy of the current cron entry list.
  167. func (c *Cron) entrySnapshot() []*Entry {
  168. entries := make([]*Entry, 0, len(c.entries))
  169. for _, e := range c.entries {
  170. entries = append(entries, &Entry{
  171. Description: e.Description,
  172. Spec: e.Spec,
  173. Schedule: e.Schedule,
  174. Next: e.Next,
  175. Prev: e.Prev,
  176. Job: e.Job,
  177. ExecTimes: e.ExecTimes,
  178. })
  179. }
  180. return entries
  181. }