cron.go 8.6 KB

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