cron.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. package cron
  2. import (
  3. "sort"
  4. "time"
  5. )
  6. // Cron keeps track of any number of entries, invoking the associated func as
  7. // specified by the schedule. It may be started, stopped, and the entries may
  8. // be inspected while running.
  9. type Cron struct {
  10. entries []*Entry
  11. chain Chain
  12. stop chan struct{}
  13. add chan *Entry
  14. remove chan EntryID
  15. snapshot chan chan []Entry
  16. running bool
  17. logger Logger
  18. location *time.Location
  19. parser Parser
  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. // WrappedJob is the thing to run when the Schedule is activated.
  47. WrappedJob Job
  48. // Job is the thing that was submitted to cron.
  49. // It is kept around so that user code that needs to get at the job later,
  50. // e.g. via Entries() can do so.
  51. Job Job
  52. }
  53. // Valid returns true if this is not the zero entry.
  54. func (e Entry) Valid() bool { return e.ID != 0 }
  55. // byTime is a wrapper for sorting the entry array by time
  56. // (with zero time at the end).
  57. type byTime []*Entry
  58. func (s byTime) Len() int { return len(s) }
  59. func (s byTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  60. func (s byTime) Less(i, j int) bool {
  61. // Two zero times should return false.
  62. // Otherwise, zero is "greater" than any other time.
  63. // (To sort it at the end of the list.)
  64. if s[i].Next.IsZero() {
  65. return false
  66. }
  67. if s[j].Next.IsZero() {
  68. return true
  69. }
  70. return s[i].Next.Before(s[j].Next)
  71. }
  72. // New returns a new Cron job runner, modified by the given options.
  73. //
  74. // Available Settings
  75. //
  76. // Time Zone
  77. // Description: The time zone in which schedules are interpreted
  78. // Default: time.Local
  79. //
  80. // Parser
  81. // Description: Parser converts cron spec strings into cron.Schedules.
  82. // Default: Accepts this spec: https://en.wikipedia.org/wiki/Cron
  83. //
  84. // Chain
  85. // Description: Wrap submitted jobs to customize behavior.
  86. // Default: A chain that recovers panics.
  87. //
  88. // See "cron.With*" to modify the default behavior.
  89. func New(opts ...Option) *Cron {
  90. c := &Cron{
  91. entries: nil,
  92. chain: NewChain(),
  93. add: make(chan *Entry),
  94. stop: make(chan struct{}),
  95. snapshot: make(chan chan []Entry),
  96. remove: make(chan EntryID),
  97. running: false,
  98. logger: DefaultLogger,
  99. location: time.Local,
  100. parser: standardParser,
  101. }
  102. for _, opt := range opts {
  103. opt(c)
  104. }
  105. return c
  106. }
  107. // FuncJob is a wrapper that turns a func() into a cron.Job
  108. type FuncJob func()
  109. func (f FuncJob) Run() { f() }
  110. // AddFunc adds a func to the Cron to be run on the given schedule.
  111. // The spec is parsed using the time zone of this Cron instance as the default.
  112. // An opaque ID is returned that can be used to later remove it.
  113. func (c *Cron) AddFunc(spec string, cmd func()) (EntryID, error) {
  114. return c.AddJob(spec, FuncJob(cmd))
  115. }
  116. // AddJob adds a Job to the Cron to be run on the given schedule.
  117. // The spec is parsed using the time zone of this Cron instance as the default.
  118. // An opaque ID is returned that can be used to later remove it.
  119. func (c *Cron) AddJob(spec string, cmd Job) (EntryID, error) {
  120. schedule, err := c.parser.Parse(spec)
  121. if err != nil {
  122. return 0, err
  123. }
  124. return c.Schedule(schedule, cmd), nil
  125. }
  126. // Schedule adds a Job to the Cron to be run on the given schedule.
  127. // The job is wrapped with the configured Chain.
  128. func (c *Cron) Schedule(schedule Schedule, cmd Job) EntryID {
  129. c.nextID++
  130. entry := &Entry{
  131. ID: c.nextID,
  132. Schedule: schedule,
  133. WrappedJob: c.chain.Then(cmd),
  134. Job: cmd,
  135. }
  136. if !c.running {
  137. c.entries = append(c.entries, entry)
  138. } else {
  139. c.add <- entry
  140. }
  141. return entry.ID
  142. }
  143. // Entries returns a snapshot of the cron entries.
  144. func (c *Cron) Entries() []Entry {
  145. if c.running {
  146. replyChan := make(chan []Entry, 1)
  147. c.snapshot <- replyChan
  148. return <-replyChan
  149. }
  150. return c.entrySnapshot()
  151. }
  152. // Location gets the time zone location
  153. func (c *Cron) Location() *time.Location {
  154. return c.location
  155. }
  156. // Entry returns a snapshot of the given entry, or nil if it couldn't be found.
  157. func (c *Cron) Entry(id EntryID) Entry {
  158. for _, entry := range c.Entries() {
  159. if id == entry.ID {
  160. return entry
  161. }
  162. }
  163. return Entry{}
  164. }
  165. // Remove an entry from being run in the future.
  166. func (c *Cron) Remove(id EntryID) {
  167. if c.running {
  168. c.remove <- id
  169. } else {
  170. c.removeEntry(id)
  171. }
  172. }
  173. // Start the cron scheduler in its own goroutine, or no-op if already started.
  174. func (c *Cron) Start() {
  175. if c.running {
  176. return
  177. }
  178. c.running = true
  179. go c.run()
  180. }
  181. // Run the cron scheduler, or no-op if already running.
  182. func (c *Cron) Run() {
  183. if c.running {
  184. return
  185. }
  186. c.running = true
  187. c.run()
  188. }
  189. // run the scheduler.. this is private just due to the need to synchronize
  190. // access to the 'running' state variable.
  191. func (c *Cron) run() {
  192. c.logger.Info("start")
  193. // Figure out the next activation times for each entry.
  194. now := c.now()
  195. for _, entry := range c.entries {
  196. entry.Next = entry.Schedule.Next(now)
  197. c.logger.Info("schedule", "now", now, "entry", entry.ID, "next", entry.Next)
  198. }
  199. for {
  200. // Determine the next entry to run.
  201. sort.Sort(byTime(c.entries))
  202. var timer *time.Timer
  203. if len(c.entries) == 0 || c.entries[0].Next.IsZero() {
  204. // If there are no entries yet, just sleep - it still handles new entries
  205. // and stop requests.
  206. timer = time.NewTimer(100000 * time.Hour)
  207. } else {
  208. timer = time.NewTimer(c.entries[0].Next.Sub(now))
  209. }
  210. for {
  211. select {
  212. case now = <-timer.C:
  213. now = now.In(c.location)
  214. c.logger.Info("wake", "now", now)
  215. // Run every entry whose next time was less than now
  216. for _, e := range c.entries {
  217. if e.Next.After(now) || e.Next.IsZero() {
  218. break
  219. }
  220. go e.WrappedJob.Run()
  221. e.Prev = e.Next
  222. e.Next = e.Schedule.Next(now)
  223. c.logger.Info("run", "now", now, "entry", e.ID, "next", e.Next)
  224. }
  225. case newEntry := <-c.add:
  226. timer.Stop()
  227. now = c.now()
  228. newEntry.Next = newEntry.Schedule.Next(now)
  229. c.entries = append(c.entries, newEntry)
  230. c.logger.Info("added", "now", now, "entry", newEntry.ID, "next", newEntry.Next)
  231. case replyChan := <-c.snapshot:
  232. replyChan <- c.entrySnapshot()
  233. continue
  234. case <-c.stop:
  235. timer.Stop()
  236. c.logger.Info("stop")
  237. return
  238. case id := <-c.remove:
  239. timer.Stop()
  240. now = c.now()
  241. c.removeEntry(id)
  242. c.logger.Info("removed", "entry", id)
  243. }
  244. break
  245. }
  246. }
  247. }
  248. // now returns current time in c location
  249. func (c *Cron) now() time.Time {
  250. return time.Now().In(c.location)
  251. }
  252. // Stop stops the cron scheduler if it is running; otherwise it does nothing.
  253. func (c *Cron) Stop() {
  254. if !c.running {
  255. return
  256. }
  257. c.stop <- struct{}{}
  258. c.running = false
  259. }
  260. // entrySnapshot returns a copy of the current cron entry list.
  261. func (c *Cron) entrySnapshot() []Entry {
  262. var entries = make([]Entry, len(c.entries))
  263. for i, e := range c.entries {
  264. entries[i] = *e
  265. }
  266. return entries
  267. }
  268. func (c *Cron) removeEntry(id EntryID) {
  269. var entries []*Entry
  270. for _, e := range c.entries {
  271. if e.ID != id {
  272. entries = append(entries, e)
  273. }
  274. }
  275. c.entries = entries
  276. }