cron.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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 []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 []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. c.snapshot <- nil
  142. return <-c.snapshot
  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. c.logf("cron: panic running job: %v\n%s", r, buf)
  190. }
  191. }()
  192. j.Run()
  193. }
  194. // run the scheduler.. this is private just due to the need to synchronize
  195. // access to the 'running' state variable.
  196. func (c *Cron) run() {
  197. // Figure out the next activation times for each entry.
  198. now := c.now()
  199. for _, entry := range c.entries {
  200. entry.Next = entry.Schedule.Next(now)
  201. }
  202. for {
  203. // Determine the next entry to run.
  204. sort.Sort(byTime(c.entries))
  205. var timer *time.Timer
  206. if len(c.entries) == 0 || c.entries[0].Next.IsZero() {
  207. // If there are no entries yet, just sleep - it still handles new entries
  208. // and stop requests.
  209. timer = time.NewTimer(100000 * time.Hour)
  210. } else {
  211. timer = time.NewTimer(c.entries[0].Next.Sub(now))
  212. }
  213. for {
  214. select {
  215. case now = <-timer.C:
  216. now = now.In(c.location)
  217. // Run every entry whose next time was less than now
  218. for _, e := range c.entries {
  219. if e.Next.After(now) || e.Next.IsZero() {
  220. break
  221. }
  222. go c.runWithRecovery(e.Job)
  223. e.Prev = e.Next
  224. e.Next = e.Schedule.Next(now)
  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. case <-c.snapshot:
  232. c.snapshot <- c.entrySnapshot()
  233. continue
  234. case <-c.stop:
  235. timer.Stop()
  236. return
  237. case id := <-c.remove:
  238. timer.Stop()
  239. c.removeEntry(id)
  240. }
  241. break
  242. }
  243. }
  244. }
  245. // now returns current time in c location
  246. func (c *Cron) now() time.Time {
  247. return time.Now().In(c.location)
  248. }
  249. // Logs an error to stderr or to the configured error log
  250. func (c *Cron) logf(format string, args ...interface{}) {
  251. c.logger.Printf(format, args...)
  252. }
  253. // Stop stops the cron scheduler if it is running; otherwise it does nothing.
  254. func (c *Cron) Stop() {
  255. if !c.running {
  256. return
  257. }
  258. c.stop <- struct{}{}
  259. c.running = false
  260. }
  261. // entrySnapshot returns a copy of the current cron entry list.
  262. func (c *Cron) entrySnapshot() []Entry {
  263. var entries = make([]Entry, len(c.entries))
  264. for i, e := range c.entries {
  265. entries[i] = *e
  266. }
  267. return entries
  268. }
  269. func (c *Cron) removeEntry(id EntryID) {
  270. var entries []*Entry
  271. for _, e := range c.entries {
  272. if e.ID != id {
  273. entries = append(entries, e)
  274. }
  275. }
  276. c.entries = entries
  277. }