cron.go 8.1 KB

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