cron.go 8.2 KB

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