cron.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. package cron
  2. import (
  3. "log"
  4. "os"
  5. "runtime"
  6. "sort"
  7. "time"
  8. )
  9. // Cron keeps track of any number of entries, invoking the associated func as
  10. // specified by the schedule. It may be started, stopped, and the entries may
  11. // be inspected while running.
  12. type Cron struct {
  13. entries []*Entry
  14. stop chan struct{}
  15. add chan *Entry
  16. remove chan EntryID
  17. snapshot chan chan []Entry
  18. running bool
  19. logger *log.Logger
  20. location *time.Location
  21. parser Parser
  22. nextID EntryID
  23. }
  24. // Job is an interface for submitted cron jobs.
  25. type Job interface {
  26. Run()
  27. }
  28. // Schedule describes a job's duty cycle.
  29. type Schedule interface {
  30. // Next returns the next activation time, later than the given time.
  31. // Next is invoked initially, and then each time the job is run.
  32. Next(time.Time) time.Time
  33. }
  34. // EntryID identifies an entry within a Cron instance
  35. type EntryID int
  36. // Entry consists of a schedule and the func to execute on that schedule.
  37. type Entry struct {
  38. // ID is the cron-assigned ID of this entry, which may be used to look up a
  39. // snapshot or remove it.
  40. ID EntryID
  41. // Schedule on which this job should be run.
  42. Schedule Schedule
  43. // Next time the job will run, or the zero time if Cron has not been
  44. // started or this entry's schedule is unsatisfiable
  45. Next time.Time
  46. // Prev is the last time this job was run, or the zero time if never.
  47. Prev time.Time
  48. // Job is the thing to run when the Schedule is activated.
  49. Job Job
  50. }
  51. // Valid returns true if this is not the zero entry.
  52. func (e Entry) Valid() bool { return e.ID != 0 }
  53. // byTime is a wrapper for sorting the entry array by time
  54. // (with zero time at the end).
  55. type byTime []*Entry
  56. func (s byTime) Len() int { return len(s) }
  57. func (s byTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  58. func (s byTime) Less(i, j int) bool {
  59. // Two zero times should return false.
  60. // Otherwise, zero is "greater" than any other time.
  61. // (To sort it at the end of the list.)
  62. if s[i].Next.IsZero() {
  63. return false
  64. }
  65. if s[j].Next.IsZero() {
  66. return true
  67. }
  68. return s[i].Next.Before(s[j].Next)
  69. }
  70. // New returns a new Cron job runner, modified by the given options.
  71. //
  72. // Available Settings
  73. //
  74. // Time Zone
  75. // Description: The time zone in which schedules are interpreted
  76. // Default: time.Local
  77. //
  78. // PanicLogger
  79. // Description: How to log Jobs that panic
  80. // Default: Log the panic to os.Stderr
  81. //
  82. // Parser
  83. // Description:
  84. // Default: Parser that accepts the spec described here: https://en.wikipedia.org/wiki/Cron
  85. //
  86. // See "cron.With*" to modify the default behavior.
  87. func New(opts ...Option) *Cron {
  88. c := &Cron{
  89. entries: nil,
  90. add: make(chan *Entry),
  91. stop: make(chan struct{}),
  92. snapshot: make(chan chan []Entry),
  93. remove: make(chan EntryID),
  94. running: false,
  95. logger: log.New(os.Stderr, "", log.LstdFlags),
  96. location: time.Local,
  97. parser: standardParser,
  98. }
  99. for _, opt := range opts {
  100. opt(c)
  101. }
  102. return c
  103. }
  104. // FuncJob is a wrapper that turns a func() into a cron.Job
  105. type FuncJob func()
  106. func (f FuncJob) Run() { f() }
  107. // AddFunc adds a func to the Cron to be run on the given schedule.
  108. // The spec is parsed using the time zone of this Cron instance as the default.
  109. // An opaque ID is returned that can be used to later remove it.
  110. func (c *Cron) AddFunc(spec string, cmd func()) (EntryID, error) {
  111. return c.AddJob(spec, FuncJob(cmd))
  112. }
  113. // AddJob adds a Job to the Cron to be run on the given schedule.
  114. // The spec is parsed using the time zone of this Cron instance as the default.
  115. // An opaque ID is returned that can be used to later remove it.
  116. func (c *Cron) AddJob(spec string, cmd Job) (EntryID, error) {
  117. schedule, err := c.parser.Parse(spec)
  118. if err != nil {
  119. return 0, err
  120. }
  121. return c.Schedule(schedule, cmd), nil
  122. }
  123. // Schedule adds a Job to the Cron to be run on the given schedule.
  124. func (c *Cron) Schedule(schedule Schedule, cmd Job) EntryID {
  125. c.nextID++
  126. entry := &Entry{
  127. ID: c.nextID,
  128. Schedule: schedule,
  129. Job: cmd,
  130. }
  131. if !c.running {
  132. c.entries = append(c.entries, entry)
  133. } else {
  134. c.add <- entry
  135. }
  136. return entry.ID
  137. }
  138. // Entries returns a snapshot of the cron entries.
  139. func (c *Cron) Entries() []Entry {
  140. if c.running {
  141. replyChan := make(chan []Entry, 1)
  142. c.snapshot <- replyChan
  143. return <-replyChan
  144. }
  145. return c.entrySnapshot()
  146. }
  147. // Location gets the time zone location
  148. func (c *Cron) Location() *time.Location {
  149. return c.location
  150. }
  151. // Entry returns a snapshot of the given entry, or nil if it couldn't be found.
  152. func (c *Cron) Entry(id EntryID) Entry {
  153. for _, entry := range c.Entries() {
  154. if id == entry.ID {
  155. return entry
  156. }
  157. }
  158. return Entry{}
  159. }
  160. // Remove an entry from being run in the future.
  161. func (c *Cron) Remove(id EntryID) {
  162. if c.running {
  163. c.remove <- id
  164. } else {
  165. c.removeEntry(id)
  166. }
  167. }
  168. // Start the cron scheduler in its own goroutine, or no-op if already started.
  169. func (c *Cron) Start() {
  170. if c.running {
  171. return
  172. }
  173. c.running = true
  174. go c.run()
  175. }
  176. // Run the cron scheduler, or no-op if already running.
  177. func (c *Cron) Run() {
  178. if c.running {
  179. return
  180. }
  181. c.running = true
  182. c.run()
  183. }
  184. func (c *Cron) runWithRecovery(j Job) {
  185. defer func() {
  186. if r := recover(); r != nil {
  187. const size = 64 << 10
  188. buf := make([]byte, size)
  189. buf = buf[:runtime.Stack(buf, false)]
  190. c.logf("cron: panic running job: %v\n%s", r, buf)
  191. }
  192. }()
  193. j.Run()
  194. }
  195. // run the scheduler.. this is private just due to the need to synchronize
  196. // access to the 'running' state variable.
  197. func (c *Cron) run() {
  198. // Figure out the next activation times for each entry.
  199. now := c.now()
  200. for _, entry := range c.entries {
  201. entry.Next = entry.Schedule.Next(now)
  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. // Run every entry whose next time was less than now
  219. for _, e := range c.entries {
  220. if e.Next.After(now) || e.Next.IsZero() {
  221. break
  222. }
  223. go c.runWithRecovery(e.Job)
  224. e.Prev = e.Next
  225. e.Next = e.Schedule.Next(now)
  226. }
  227. case newEntry := <-c.add:
  228. timer.Stop()
  229. now = c.now()
  230. newEntry.Next = newEntry.Schedule.Next(now)
  231. c.entries = append(c.entries, newEntry)
  232. case replyChan := <-c.snapshot:
  233. replyChan <- c.entrySnapshot()
  234. continue
  235. case <-c.stop:
  236. timer.Stop()
  237. return
  238. case id := <-c.remove:
  239. timer.Stop()
  240. c.removeEntry(id)
  241. }
  242. break
  243. }
  244. }
  245. }
  246. // now returns current time in c location
  247. func (c *Cron) now() time.Time {
  248. return time.Now().In(c.location)
  249. }
  250. // Logs an error to stderr or to the configured error log
  251. func (c *Cron) logf(format string, args ...interface{}) {
  252. c.logger.Printf(format, args...)
  253. }
  254. // Stop stops the cron scheduler if it is running; otherwise it does nothing.
  255. func (c *Cron) Stop() {
  256. if !c.running {
  257. return
  258. }
  259. c.stop <- struct{}{}
  260. c.running = false
  261. }
  262. // entrySnapshot returns a copy of the current cron entry list.
  263. func (c *Cron) entrySnapshot() []Entry {
  264. var entries = make([]Entry, len(c.entries))
  265. for i, e := range c.entries {
  266. entries[i] = *e
  267. }
  268. return entries
  269. }
  270. func (c *Cron) removeEntry(id EntryID) {
  271. var entries []*Entry
  272. for _, e := range c.entries {
  273. if e.ID != id {
  274. entries = append(entries, e)
  275. }
  276. }
  277. c.entries = entries
  278. }