schedule.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. package cron
  2. import (
  3. "strconv"
  4. "strings"
  5. "time"
  6. "github.com/pkg/errors"
  7. )
  8. // Moment represents a parsed single time moment.
  9. type Moment struct {
  10. Minute int `json:"minute"`
  11. Hour int `json:"hour"`
  12. Day int `json:"day"`
  13. Month int `json:"month"`
  14. DayOfWeek int `json:"dayOfWeek"`
  15. }
  16. // NewMoment creates a new Moment from the specified time.
  17. func NewMoment(t time.Time) *Moment {
  18. return &Moment{
  19. Minute: t.Minute(),
  20. Hour: t.Hour(),
  21. Day: t.Day(),
  22. Month: int(t.Month()),
  23. DayOfWeek: int(t.Weekday()),
  24. }
  25. }
  26. // Schedule stores parsed information for each time component when a cron job should run.
  27. type Schedule struct {
  28. Minutes map[int]struct{} `json:"minutes"`
  29. Hours map[int]struct{} `json:"hours"`
  30. Days map[int]struct{} `json:"days"`
  31. Months map[int]struct{} `json:"months"`
  32. DaysOfWeek map[int]struct{} `json:"daysOfWeek"`
  33. }
  34. // IsDue checks whether the provided Moment satisfies the current Schedule.
  35. func (s *Schedule) IsDue(m *Moment) bool {
  36. if _, ok := s.Minutes[m.Minute]; !ok {
  37. return false
  38. }
  39. if _, ok := s.Hours[m.Hour]; !ok {
  40. return false
  41. }
  42. if _, ok := s.Days[m.Day]; !ok {
  43. return false
  44. }
  45. if _, ok := s.DaysOfWeek[m.DayOfWeek]; !ok {
  46. return false
  47. }
  48. if _, ok := s.Months[m.Month]; !ok {
  49. return false
  50. }
  51. return true
  52. }
  53. // NewSchedule creates a new Schedule from a cron expression.
  54. //
  55. // A cron expression is consisted of 5 segments separated by space,
  56. // representing: minute, hour, day of the month, month and day of the week.
  57. //
  58. // Each segment could be in the following formats:
  59. // - wildcard: *
  60. // - range: 1-30
  61. // - step: */n or 1-30/n
  62. // - list: 1,2,3,10-20/n
  63. func NewSchedule(cronExpr string) (*Schedule, error) {
  64. segments := strings.Split(cronExpr, " ")
  65. if len(segments) != 5 {
  66. return nil, errors.New("invalid cron expression - must have exactly 5 space separated segments")
  67. }
  68. minutes, err := parseCronSegment(segments[0], 0, 59)
  69. if err != nil {
  70. return nil, err
  71. }
  72. hours, err := parseCronSegment(segments[1], 0, 23)
  73. if err != nil {
  74. return nil, err
  75. }
  76. days, err := parseCronSegment(segments[2], 1, 31)
  77. if err != nil {
  78. return nil, err
  79. }
  80. months, err := parseCronSegment(segments[3], 1, 12)
  81. if err != nil {
  82. return nil, err
  83. }
  84. daysOfWeek, err := parseCronSegment(segments[4], 0, 6)
  85. if err != nil {
  86. return nil, err
  87. }
  88. return &Schedule{
  89. Minutes: minutes,
  90. Hours: hours,
  91. Days: days,
  92. Months: months,
  93. DaysOfWeek: daysOfWeek,
  94. }, nil
  95. }
  96. // parseCronSegment parses a single cron expression segment and
  97. // returns its time schedule slots.
  98. func parseCronSegment(segment string, min int, max int) (map[int]struct{}, error) {
  99. slots := map[int]struct{}{}
  100. list := strings.Split(segment, ",")
  101. for _, p := range list {
  102. stepParts := strings.Split(p, "/")
  103. // step (*/n, 1-30/n)
  104. var step int
  105. switch len(stepParts) {
  106. case 1:
  107. step = 1
  108. case 2:
  109. parsedStep, err := strconv.Atoi(stepParts[1])
  110. if err != nil {
  111. return nil, err
  112. }
  113. if parsedStep < 1 || parsedStep > max {
  114. return nil, errors.Errorf("invalid segment step boundary - the step must be between 1 and the %d", max)
  115. }
  116. step = parsedStep
  117. default:
  118. return nil, errors.New("invalid segment step format - must be in the format */n or 1-30/n")
  119. }
  120. // find the min and max range of the segment part
  121. var rangeMin, rangeMax int
  122. if stepParts[0] == "*" {
  123. rangeMin = min
  124. rangeMax = max
  125. } else {
  126. // single digit (1) or range (1-30)
  127. rangeParts := strings.Split(stepParts[0], "-")
  128. switch len(rangeParts) {
  129. case 1:
  130. if step != 1 {
  131. return nil, errors.New("invalid segment step - step > 1 could be used only with the wildcard or range format")
  132. }
  133. parsed, err := strconv.Atoi(rangeParts[0])
  134. if err != nil {
  135. return nil, err
  136. }
  137. if parsed < min || parsed > max {
  138. return nil, errors.New("invalid segment value - must be between the min and max of the segment")
  139. }
  140. rangeMin = parsed
  141. rangeMax = rangeMin
  142. case 2:
  143. parsedMin, err := strconv.Atoi(rangeParts[0])
  144. if err != nil {
  145. return nil, err
  146. }
  147. if parsedMin < min || parsedMin > max {
  148. return nil, errors.Errorf("invalid segment range minimum - must be between %d and %d", min, max)
  149. }
  150. rangeMin = parsedMin
  151. parsedMax, err := strconv.Atoi(rangeParts[1])
  152. if err != nil {
  153. return nil, err
  154. }
  155. if parsedMax < parsedMin || parsedMax > max {
  156. return nil, errors.Errorf("invalid segment range maximum - must be between %d and %d", rangeMin, max)
  157. }
  158. rangeMax = parsedMax
  159. default:
  160. return nil, errors.New("invalid segment range format - the range must have 1 or 2 parts")
  161. }
  162. }
  163. // fill the slots
  164. for i := rangeMin; i <= rangeMax; i += step {
  165. slots[i] = struct{}{}
  166. }
  167. }
  168. return slots, nil
  169. }