cron.go 8.6 KB

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