cron.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. package cron
  2. import (
  3. "fmt"
  4. "runtime"
  5. "sort"
  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. stop chan struct{}
  14. add chan *Entry
  15. remove chan EntryID
  16. snapshot chan chan []Entry
  17. running bool
  18. logger 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. // Job is the thing to run when the Schedule is activated.
  48. Job Job
  49. }
  50. // Valid returns true if this is not the zero entry.
  51. func (e Entry) Valid() bool { return e.ID != 0 }
  52. // byTime is a wrapper for sorting the entry array by time
  53. // (with zero time at the end).
  54. type byTime []*Entry
  55. func (s byTime) Len() int { return len(s) }
  56. func (s byTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  57. func (s byTime) Less(i, j int) bool {
  58. // Two zero times should return false.
  59. // Otherwise, zero is "greater" than any other time.
  60. // (To sort it at the end of the list.)
  61. if s[i].Next.IsZero() {
  62. return false
  63. }
  64. if s[j].Next.IsZero() {
  65. return true
  66. }
  67. return s[i].Next.Before(s[j].Next)
  68. }
  69. // New returns a new Cron job runner, modified by the given options.
  70. //
  71. // Available Settings
  72. //
  73. // Time Zone
  74. // Description: The time zone in which schedules are interpreted
  75. // Default: time.Local
  76. //
  77. // PanicLogger
  78. // Description: How to log Jobs that panic
  79. // Default: Log the panic to os.Stderr
  80. //
  81. // Parser
  82. // Description:
  83. // Default: Parser that accepts the spec described here: https://en.wikipedia.org/wiki/Cron
  84. //
  85. // See "cron.With*" to modify the default behavior.
  86. func New(opts ...Option) *Cron {
  87. c := &Cron{
  88. entries: nil,
  89. add: make(chan *Entry),
  90. stop: make(chan struct{}),
  91. snapshot: make(chan chan []Entry),
  92. remove: make(chan EntryID),
  93. running: false,
  94. logger: DefaultLogger,
  95. location: time.Local,
  96. parser: standardParser,
  97. }
  98. for _, opt := range opts {
  99. opt(c)
  100. }
  101. return c
  102. }
  103. // FuncJob is a wrapper that turns a func() into a cron.Job
  104. type FuncJob func()
  105. func (f FuncJob) Run() { f() }
  106. // AddFunc adds a func to the Cron to be run on the given schedule.
  107. // The spec is parsed using the time zone of this Cron instance as the default.
  108. // An opaque ID is returned that can be used to later remove it.
  109. func (c *Cron) AddFunc(spec string, cmd func()) (EntryID, error) {
  110. return c.AddJob(spec, FuncJob(cmd))
  111. }
  112. // AddJob adds a Job to the Cron to be run on the given schedule.
  113. // The spec is parsed using the time zone of this Cron instance as the default.
  114. // An opaque ID is returned that can be used to later remove it.
  115. func (c *Cron) AddJob(spec string, cmd Job) (EntryID, error) {
  116. schedule, err := c.parser.Parse(spec)
  117. if err != nil {
  118. return 0, err
  119. }
  120. return c.Schedule(schedule, cmd), nil
  121. }
  122. // Schedule adds a Job to the Cron to be run on the given schedule.
  123. func (c *Cron) Schedule(schedule Schedule, cmd Job) EntryID {
  124. c.nextID++
  125. entry := &Entry{
  126. ID: c.nextID,
  127. Schedule: schedule,
  128. Job: cmd,
  129. }
  130. if !c.running {
  131. c.entries = append(c.entries, entry)
  132. } else {
  133. c.add <- entry
  134. }
  135. return entry.ID
  136. }
  137. // Entries returns a snapshot of the cron entries.
  138. func (c *Cron) Entries() []Entry {
  139. if c.running {
  140. replyChan := make(chan []Entry, 1)
  141. c.snapshot <- replyChan
  142. return <-replyChan
  143. }
  144. return c.entrySnapshot()
  145. }
  146. // Location gets the time zone location
  147. func (c *Cron) Location() *time.Location {
  148. return c.location
  149. }
  150. // Entry returns a snapshot of the given entry, or nil if it couldn't be found.
  151. func (c *Cron) Entry(id EntryID) Entry {
  152. for _, entry := range c.Entries() {
  153. if id == entry.ID {
  154. return entry
  155. }
  156. }
  157. return Entry{}
  158. }
  159. // Remove an entry from being run in the future.
  160. func (c *Cron) Remove(id EntryID) {
  161. if c.running {
  162. c.remove <- id
  163. } else {
  164. c.removeEntry(id)
  165. }
  166. }
  167. // Start the cron scheduler in its own goroutine, or no-op if already started.
  168. func (c *Cron) Start() {
  169. if c.running {
  170. return
  171. }
  172. c.running = true
  173. go c.run()
  174. }
  175. // Run the cron scheduler, or no-op if already running.
  176. func (c *Cron) Run() {
  177. if c.running {
  178. return
  179. }
  180. c.running = true
  181. c.run()
  182. }
  183. func (c *Cron) runWithRecovery(j Job) {
  184. defer func() {
  185. if r := recover(); r != nil {
  186. const size = 64 << 10
  187. buf := make([]byte, size)
  188. buf = buf[:runtime.Stack(buf, false)]
  189. var err error
  190. err, ok := r.(error)
  191. if !ok {
  192. err = fmt.Errorf("%v", r)
  193. }
  194. c.logger.Error(err, "panic running job", "stack", "...\n"+string(buf))
  195. }
  196. }()
  197. j.Run()
  198. }
  199. // run the scheduler.. this is private just due to the need to synchronize
  200. // access to the 'running' state variable.
  201. func (c *Cron) run() {
  202. c.logger.Info("start")
  203. // Figure out the next activation times for each entry.
  204. now := c.now()
  205. for _, entry := range c.entries {
  206. entry.Next = entry.Schedule.Next(now)
  207. c.logger.Info("schedule", "now", now, "entry", entry.ID, "next", entry.Next)
  208. }
  209. for {
  210. // Determine the next entry to run.
  211. sort.Sort(byTime(c.entries))
  212. var timer *time.Timer
  213. if len(c.entries) == 0 || c.entries[0].Next.IsZero() {
  214. // If there are no entries yet, just sleep - it still handles new entries
  215. // and stop requests.
  216. timer = time.NewTimer(100000 * time.Hour)
  217. } else {
  218. timer = time.NewTimer(c.entries[0].Next.Sub(now))
  219. }
  220. for {
  221. select {
  222. case now = <-timer.C:
  223. now = now.In(c.location)
  224. c.logger.Info("wake", "now", now)
  225. // Run every entry whose next time was less than now
  226. for _, e := range c.entries {
  227. if e.Next.After(now) || e.Next.IsZero() {
  228. break
  229. }
  230. go c.runWithRecovery(e.Job)
  231. e.Prev = e.Next
  232. e.Next = e.Schedule.Next(now)
  233. c.logger.Info("run", "now", now, "entry", e.ID, "next", e.Next)
  234. }
  235. case newEntry := <-c.add:
  236. timer.Stop()
  237. now = c.now()
  238. newEntry.Next = newEntry.Schedule.Next(now)
  239. c.entries = append(c.entries, newEntry)
  240. c.logger.Info("added", "now", now, "entry", newEntry.ID, "next", newEntry.Next)
  241. case replyChan := <-c.snapshot:
  242. replyChan <- c.entrySnapshot()
  243. continue
  244. case <-c.stop:
  245. timer.Stop()
  246. c.logger.Info("stop")
  247. return
  248. case id := <-c.remove:
  249. timer.Stop()
  250. now = c.now()
  251. c.removeEntry(id)
  252. c.logger.Info("removed", "entry", id)
  253. }
  254. break
  255. }
  256. }
  257. }
  258. // now returns current time in c location
  259. func (c *Cron) now() time.Time {
  260. return time.Now().In(c.location)
  261. }
  262. // Stop stops the cron scheduler if it is running; otherwise it does nothing.
  263. func (c *Cron) Stop() {
  264. if !c.running {
  265. return
  266. }
  267. c.stop <- struct{}{}
  268. c.running = false
  269. }
  270. // entrySnapshot returns a copy of the current cron entry list.
  271. func (c *Cron) entrySnapshot() []Entry {
  272. var entries = make([]Entry, len(c.entries))
  273. for i, e := range c.entries {
  274. entries[i] = *e
  275. }
  276. return entries
  277. }
  278. func (c *Cron) removeEntry(id EntryID) {
  279. var entries []*Entry
  280. for _, e := range c.entries {
  281. if e.ID != id {
  282. entries = append(entries, e)
  283. }
  284. }
  285. c.entries = entries
  286. }