cron.go 9.0 KB

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