cron.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. remove chan EntryID
  16. snapshot chan []Entry
  17. running bool
  18. ErrorLog *log.Logger
  19. location *time.Location
  20. nextID EntryID
  21. }
  22. // Job is an interface for submitted cron jobs.
  23. type Job interface {
  24. Run()
  25. }
  26. // Schedule describes a job's duty cycle.
  27. type Schedule interface {
  28. // Next returns 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. // EntryID identifies an entry within a Cron instance
  33. type EntryID int
  34. // Entry consists of a schedule and the func to execute on that schedule.
  35. type Entry struct {
  36. // ID is the cron-assigned ID of this entry, which may be used to look up a
  37. // snapshot or remove it.
  38. ID EntryID
  39. // Schedule on which this job should be run.
  40. Schedule Schedule
  41. // Next time the job will run, or the zero time if Cron has not been
  42. // started or this entry's schedule is unsatisfiable
  43. Next time.Time
  44. // Prev is the last time this job was run, or the zero time if never.
  45. Prev time.Time
  46. // Job is the thing to run when the Schedule is activated.
  47. Job Job
  48. }
  49. // Valid returns true if this is not the zero entry.
  50. func (e Entry) Valid() bool { return e.ID != 0 }
  51. // byTime is a wrapper for sorting the entry array by time
  52. // (with zero time at the end).
  53. type byTime []*Entry
  54. func (s byTime) Len() int { return len(s) }
  55. func (s byTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  56. func (s byTime) Less(i, j int) bool {
  57. // Two zero times should return false.
  58. // Otherwise, zero is "greater" than any other time.
  59. // (To sort it at the end of the list.)
  60. if s[i].Next.IsZero() {
  61. return false
  62. }
  63. if s[j].Next.IsZero() {
  64. return true
  65. }
  66. return s[i].Next.Before(s[j].Next)
  67. }
  68. // New returns a new Cron job runner.
  69. // Jobs added to this cron are interpreted in the Local time zone by default.
  70. func New() *Cron {
  71. return NewWithLocation(time.Local)
  72. }
  73. // NewWithLocation returns a new Cron job runner in the given time zone.
  74. // Jobs added to this cron are interpreted in this time zone unless overridden.
  75. func NewWithLocation(location *time.Location) *Cron {
  76. return &Cron{
  77. entries: nil,
  78. add: make(chan *Entry),
  79. stop: make(chan struct{}),
  80. snapshot: make(chan []Entry),
  81. remove: make(chan EntryID),
  82. running: false,
  83. ErrorLog: nil,
  84. location: location,
  85. }
  86. }
  87. // FuncJob is a wrapper that turns a func() into a cron.Job
  88. type FuncJob func()
  89. func (f FuncJob) Run() { f() }
  90. // AddFunc adds a func to the Cron to be run on the given schedule.
  91. // The spec is parsed using the time zone of this Cron instance as the default.
  92. // An opaque ID is returned that can be used to later remove it.
  93. func (c *Cron) AddFunc(spec string, cmd func()) (EntryID, error) {
  94. return c.AddJob(spec, FuncJob(cmd))
  95. }
  96. // AddJob adds a Job to the Cron to be run on the given schedule.
  97. // The spec is parsed using the time zone of this Cron instance as the default.
  98. // An opaque ID is returned that can be used to later remove it.
  99. func (c *Cron) AddJob(spec string, cmd Job) (EntryID, error) {
  100. schedule, err := Parse(spec)
  101. if err != nil {
  102. return 0, err
  103. }
  104. return c.Schedule(schedule, cmd), nil
  105. }
  106. // Schedule adds a Job to the Cron to be run on the given schedule.
  107. func (c *Cron) Schedule(schedule Schedule, cmd Job) EntryID {
  108. c.nextID++
  109. entry := &Entry{
  110. ID: c.nextID,
  111. Schedule: schedule,
  112. Job: cmd,
  113. }
  114. if !c.running {
  115. c.entries = append(c.entries, entry)
  116. } else {
  117. c.add <- entry
  118. }
  119. return entry.ID
  120. }
  121. // Entries returns a snapshot of the cron entries.
  122. func (c *Cron) Entries() []Entry {
  123. if c.running {
  124. c.snapshot <- nil
  125. return <-c.snapshot
  126. }
  127. return c.entrySnapshot()
  128. }
  129. // Location gets the time zone location
  130. func (c *Cron) Location() *time.Location {
  131. return c.location
  132. }
  133. // Entry returns a snapshot of the given entry, or nil if it couldn't be found.
  134. func (c *Cron) Entry(id EntryID) Entry {
  135. for _, entry := range c.Entries() {
  136. if id == entry.ID {
  137. return entry
  138. }
  139. }
  140. return Entry{}
  141. }
  142. // Remove an entry from being run in the future.
  143. func (c *Cron) Remove(id EntryID) {
  144. if c.running {
  145. c.remove <- id
  146. } else {
  147. c.removeEntry(id)
  148. }
  149. }
  150. // Start the cron scheduler in its own go-routine, or no-op if already started.
  151. func (c *Cron) Start() {
  152. if c.running {
  153. return
  154. }
  155. c.running = true
  156. go c.run()
  157. }
  158. // Run the cron scheduler, or no-op if already running.
  159. func (c *Cron) Run() {
  160. if c.running {
  161. return
  162. }
  163. c.running = true
  164. c.run()
  165. }
  166. func (c *Cron) runWithRecovery(j Job) {
  167. defer func() {
  168. if r := recover(); r != nil {
  169. const size = 64 << 10
  170. buf := make([]byte, size)
  171. buf = buf[:runtime.Stack(buf, false)]
  172. c.logf("cron: panic running job: %v\n%s", r, buf)
  173. }
  174. }()
  175. j.Run()
  176. }
  177. // run the scheduler.. this is private just due to the need to synchronize
  178. // access to the 'running' state variable.
  179. func (c *Cron) run() {
  180. // Figure out the next activation times for each entry.
  181. now := c.now()
  182. for _, entry := range c.entries {
  183. entry.Next = entry.Schedule.Next(now)
  184. }
  185. for {
  186. // Determine the next entry to run.
  187. sort.Sort(byTime(c.entries))
  188. var timer *time.Timer
  189. if len(c.entries) == 0 || c.entries[0].Next.IsZero() {
  190. // If there are no entries yet, just sleep - it still handles new entries
  191. // and stop requests.
  192. timer = time.NewTimer(100000 * time.Hour)
  193. } else {
  194. timer = time.NewTimer(c.entries[0].Next.Sub(now))
  195. }
  196. for {
  197. select {
  198. case now = <-timer.C:
  199. now = now.In(c.location)
  200. // Run every entry whose next time was less than now
  201. for _, e := range c.entries {
  202. if e.Next.After(now) || e.Next.IsZero() {
  203. break
  204. }
  205. go c.runWithRecovery(e.Job)
  206. e.Prev = e.Next
  207. e.Next = e.Schedule.Next(now)
  208. }
  209. case newEntry := <-c.add:
  210. timer.Stop()
  211. now = c.now()
  212. newEntry.Next = newEntry.Schedule.Next(now)
  213. c.entries = append(c.entries, newEntry)
  214. case <-c.snapshot:
  215. c.snapshot <- c.entrySnapshot()
  216. continue
  217. case <-c.stop:
  218. timer.Stop()
  219. return
  220. case id := <-c.remove:
  221. timer.Stop()
  222. c.removeEntry(id)
  223. }
  224. break
  225. }
  226. }
  227. }
  228. // now returns current time in c location
  229. func (c *Cron) now() time.Time {
  230. return time.Now().In(c.location)
  231. }
  232. // Logs an error to stderr or to the configured error log
  233. func (c *Cron) logf(format string, args ...interface{}) {
  234. if c.ErrorLog != nil {
  235. c.ErrorLog.Printf(format, args...)
  236. } else {
  237. log.Printf(format, args...)
  238. }
  239. }
  240. // Stop stops the cron scheduler if it is running; otherwise it does nothing.
  241. func (c *Cron) Stop() {
  242. if !c.running {
  243. return
  244. }
  245. c.stop <- struct{}{}
  246. c.running = false
  247. }
  248. // entrySnapshot returns a copy of the current cron entry list.
  249. func (c *Cron) entrySnapshot() []Entry {
  250. var entries = make([]Entry, len(c.entries))
  251. for i, e := range c.entries {
  252. entries[i] = *e
  253. }
  254. return entries
  255. }
  256. func (c *Cron) removeEntry(id EntryID) {
  257. var entries []*Entry
  258. for _, e := range c.entries {
  259. if e.ID != id {
  260. entries = append(entries, e)
  261. }
  262. }
  263. c.entries = entries
  264. }