doc.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. /*
  2. Package cron implements a cron spec parser and job runner.
  3. Usage
  4. Callers may register Funcs to be invoked on a given schedule. Cron will run
  5. them in their own goroutines.
  6. c := cron.New()
  7. c.AddFunc("30 * * * *", func() { fmt.Println("Every hour on the half hour") })
  8. c.AddFunc("30 3-6,20-23 * * *", func() { fmt.Println(".. in the range 3-6am, 8-11pm") })
  9. c.AddFunc("CRON_TZ=Asia/Tokyo 30 04 * * * *", func() { fmt.Println("Runs at 04:30 Tokyo time every day") })
  10. c.AddFunc("@hourly", func() { fmt.Println("Every hour") })
  11. c.AddFunc("@every 1h30m", func() { fmt.Println("Every hour thirty") })
  12. c.Start()
  13. ..
  14. // Funcs are invoked in their own goroutine, asynchronously.
  15. ...
  16. // Funcs may also be added to a running Cron
  17. c.AddFunc("@daily", func() { fmt.Println("Every day") })
  18. ..
  19. // Inspect the cron job entries' next and previous run times.
  20. inspect(c.Entries())
  21. ..
  22. c.Stop() // Stop the scheduler (does not stop any jobs already running).
  23. CRON Expression Format
  24. A cron expression represents a set of times, using 5 space-separated fields.
  25. Field name | Mandatory? | Allowed values | Allowed special characters
  26. ---------- | ---------- | -------------- | --------------------------
  27. Minutes | Yes | 0-59 | * / , -
  28. Hours | Yes | 0-23 | * / , -
  29. Day of month | Yes | 1-31 | * / , - ?
  30. Month | Yes | 1-12 or JAN-DEC | * / , -
  31. Day of week | Yes | 0-6 or SUN-SAT | * / , - ?
  32. Month and Day-of-week field values are case insensitive. "SUN", "Sun", and
  33. "sun" are equally accepted.
  34. The specific interpretation of the format is based on the Cron Wikipedia page:
  35. https://en.wikipedia.org/wiki/Cron
  36. Alternative Formats
  37. Alternative Cron expression formats support other fields like seconds. You can
  38. implement that by creating a custom Parser as follows.
  39. cron.New(
  40. cron.WithParser(
  41. cron.SecondOptional | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor))
  42. The most popular alternative Cron expression format is Quartz:
  43. http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html
  44. Special Characters
  45. Asterisk ( * )
  46. The asterisk indicates that the cron expression will match for all values of the
  47. field; e.g., using an asterisk in the 5th field (month) would indicate every
  48. month.
  49. Slash ( / )
  50. Slashes are used to describe increments of ranges. For example 3-59/15 in the
  51. 1st field (minutes) would indicate the 3rd minute of the hour and every 15
  52. minutes thereafter. The form "*\/..." is equivalent to the form "first-last/...",
  53. that is, an increment over the largest possible range of the field. The form
  54. "N/..." is accepted as meaning "N-MAX/...", that is, starting at N, use the
  55. increment until the end of that specific range. It does not wrap around.
  56. Comma ( , )
  57. Commas are used to separate items of a list. For example, using "MON,WED,FRI" in
  58. the 5th field (day of week) would mean Mondays, Wednesdays and Fridays.
  59. Hyphen ( - )
  60. Hyphens are used to define ranges. For example, 9-17 would indicate every
  61. hour between 9am and 5pm inclusive.
  62. Question mark ( ? )
  63. Question mark may be used instead of '*' for leaving either day-of-month or
  64. day-of-week blank.
  65. Predefined schedules
  66. You may use one of several pre-defined schedules in place of a cron expression.
  67. Entry | Description | Equivalent To
  68. ----- | ----------- | -------------
  69. @yearly (or @annually) | Run once a year, midnight, Jan. 1st | 0 0 1 1 *
  70. @monthly | Run once a month, midnight, first of month | 0 0 1 * *
  71. @weekly | Run once a week, midnight between Sat/Sun | 0 0 * * 0
  72. @daily (or @midnight) | Run once a day, midnight | 0 0 * * *
  73. @hourly | Run once an hour, beginning of hour | 0 * * * *
  74. Intervals
  75. You may also schedule a job to execute at fixed intervals, starting at the time it's added
  76. or cron is run. This is supported by formatting the cron spec like this:
  77. @every <duration>
  78. where "duration" is a string accepted by time.ParseDuration
  79. (http://golang.org/pkg/time/#ParseDuration).
  80. For example, "@every 1h30m10s" would indicate a schedule that activates after
  81. 1 hour, 30 minutes, 10 seconds, and then every interval after that.
  82. Note: The interval does not take the job runtime into account. For example,
  83. if a job takes 3 minutes to run, and it is scheduled to run every 5 minutes,
  84. it will have only 2 minutes of idle time between each run.
  85. Time zones
  86. By default, all interpretation and scheduling is done in the machine's local
  87. time zone (time.Local). You can specify a different time zone on construction:
  88. cron.New(
  89. cron.WithLocation(time.UTC))
  90. Individual cron schedules may also override the time zone they are to be
  91. interpreted in by providing an additional space-separated field at the beginning
  92. of the cron spec, of the form "CRON_TZ=Asia/Tokyo".
  93. For example:
  94. # Runs at 6am in time.Local
  95. cron.New().AddFunc("0 6 * * ?", ...)
  96. # Runs at 6am in America/New_York
  97. nyc, _ := time.LoadLocation("America/New_York")
  98. c := cron.New(cron.WithLocation(nyc))
  99. c.AddFunc("0 6 * * ?", ...)
  100. # Runs at 6am in Asia/Tokyo
  101. cron.New().AddFunc("CRON_TZ=Asia/Tokyo 0 6 * * ?", ...)
  102. # Runs at 6am in Asia/Tokyo
  103. c := cron.New(cron.WithLocation(nyc))
  104. c.SetLocation("America/New_York")
  105. c.AddFunc("CRON_TZ=Asia/Tokyo 0 6 * * ?", ...)
  106. The prefix "TZ=(TIME ZONE)" is also supported for legacy compatibility.
  107. Be aware that jobs scheduled during daylight-savings leap-ahead transitions will
  108. not be run!
  109. Job Wrappers / Chain
  110. A Cron runner may be configured with a chain of job wrappers to add
  111. cross-cutting functionality to all submitted jobs. For example, they may be used
  112. to achieve the following effects:
  113. - Recover any panics from jobs (activated by default)
  114. - Delay a job's execution if the previous run hasn't completed yet
  115. - Skip a job's execution if the previous run hasn't completed yet
  116. - Log each job's invocations
  117. Install wrappers using the `cron.WithChain` option.
  118. Thread safety
  119. Since the Cron service runs concurrently with the calling code, some amount of
  120. care must be taken to ensure proper synchronization.
  121. All cron methods are designed to be correctly synchronized as long as the caller
  122. ensures that invocations have a clear happens-before ordering between them.
  123. Logging
  124. Cron defines a Logger interface that is a subset of the one defined in
  125. github.com/go-logr/logr. It has two logging levels (Info and Error), and
  126. parameters are key/value pairs. This makes it possible for cron logging to plug
  127. into structured logging systems. An adapter, [Verbose]PrintfLogger, is provided
  128. to wrap the standard library *log.Logger.
  129. Implementation
  130. Cron entries are stored in an array, sorted by their next activation time. Cron
  131. sleeps until the next job is due to be run.
  132. Upon waking:
  133. - it runs each entry that is active on that second
  134. - it calculates the next run times for the jobs that were run
  135. - it re-sorts the array of entries by next activation time.
  136. - it goes to sleep until the soonest job.
  137. */
  138. package cron