cron.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. package cron
  2. import (
  3. "runtime"
  4. "sort"
  5. "time"
  6. )
  7. // Cron keeps track of any number of entries, invoking the associated func as
  8. // specified by the schedule. It may be started, stopped, and the entries may
  9. // be inspected while running.
  10. type Cron struct {
  11. entries []*Entry
  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. // 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. vlogger: nil,
  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.logger.Printf("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. c.logVerbosef("cron is starting")
  199. // Figure out the next activation times for each entry.
  200. now := c.now()
  201. for _, entry := range c.entries {
  202. entry.Next = entry.Schedule.Next(now)
  203. c.logVerbosef("(%s) scheduled entry %d for %s", now, entry.ID, entry.Next)
  204. }
  205. for {
  206. // Determine the next entry to run.
  207. sort.Sort(byTime(c.entries))
  208. var timer *time.Timer
  209. if len(c.entries) == 0 || c.entries[0].Next.IsZero() {
  210. // If there are no entries yet, just sleep - it still handles new entries
  211. // and stop requests.
  212. timer = time.NewTimer(100000 * time.Hour)
  213. } else {
  214. timer = time.NewTimer(c.entries[0].Next.Sub(now))
  215. }
  216. for {
  217. select {
  218. case now = <-timer.C:
  219. now = now.In(c.location)
  220. c.logVerbosef("(%s) woke up", now)
  221. // Run every entry whose next time was less than now
  222. for _, e := range c.entries {
  223. if e.Next.After(now) || e.Next.IsZero() {
  224. break
  225. }
  226. go c.runWithRecovery(e.Job)
  227. e.Prev = e.Next
  228. e.Next = e.Schedule.Next(now)
  229. c.logVerbosef("(%s) started entry %d, next scheduled for %s", now, e.ID, e.Next)
  230. }
  231. case newEntry := <-c.add:
  232. timer.Stop()
  233. now = c.now()
  234. newEntry.Next = newEntry.Schedule.Next(now)
  235. c.entries = append(c.entries, newEntry)
  236. c.logVerbosef("(%s) added new entry %d, scheduled for", now, newEntry.ID, newEntry.Next)
  237. case replyChan := <-c.snapshot:
  238. replyChan <- c.entrySnapshot()
  239. continue
  240. case <-c.stop:
  241. timer.Stop()
  242. c.logVerbosef("cron is stopping")
  243. return
  244. case id := <-c.remove:
  245. timer.Stop()
  246. c.removeEntry(id)
  247. c.logVerbosef("removed entry %d", id)
  248. }
  249. break
  250. }
  251. }
  252. }
  253. // logVerbosef logs a verbose message, if such a logger is configured.
  254. func (c *Cron) logVerbosef(format string, args ...interface{}) {
  255. if c.vlogger != nil {
  256. // Format any times provided as RFC3339, easier to read than default.
  257. var formattedArgs []interface{}
  258. for _, arg := range args {
  259. if t, ok := arg.(time.Time); ok {
  260. arg = t.Format(time.RFC3339)
  261. }
  262. formattedArgs = append(formattedArgs, arg)
  263. }
  264. c.vlogger.Printf(format, formattedArgs...)
  265. }
  266. }
  267. // now returns current time in c location
  268. func (c *Cron) now() time.Time {
  269. return time.Now().In(c.location)
  270. }
  271. // Stop stops the cron scheduler if it is running; otherwise it does nothing.
  272. func (c *Cron) Stop() {
  273. if !c.running {
  274. return
  275. }
  276. c.stop <- struct{}{}
  277. c.running = false
  278. }
  279. // entrySnapshot returns a copy of the current cron entry list.
  280. func (c *Cron) entrySnapshot() []Entry {
  281. var entries = make([]Entry, len(c.entries))
  282. for i, e := range c.entries {
  283. entries[i] = *e
  284. }
  285. return entries
  286. }
  287. func (c *Cron) removeEntry(id EntryID) {
  288. var entries []*Entry
  289. for _, e := range c.entries {
  290. if e.ID != id {
  291. entries = append(entries, e)
  292. }
  293. }
  294. c.entries = entries
  295. }