schedules.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. from datetime import datetime
  2. from pyparsing import Word, Literal, ZeroOrMore, Optional, Group, StringEnd, alphas
  3. from celery.utils import is_iterable
  4. from celery.utils.timeutils import timedelta_seconds, weekday, remaining
  5. __all__ = ["schedule", "crontab"]
  6. class schedule(object):
  7. relative = False
  8. def __init__(self, run_every=None, relative=False):
  9. self.run_every = run_every
  10. self.relative = relative
  11. def remaining_estimate(self, last_run_at):
  12. """Returns when the periodic task should run next as a timedelta."""
  13. return remaining(last_run_at, self.run_every, relative=self.relative)
  14. def is_due(self, last_run_at):
  15. """Returns tuple of two items ``(is_due, next_time_to_run)``,
  16. where next time to run is in seconds.
  17. See :meth:`celery.task.base.PeriodicTask.is_due` for more information.
  18. """
  19. rem_delta = self.remaining_estimate(last_run_at)
  20. rem = timedelta_seconds(rem_delta)
  21. if rem == 0:
  22. return True, timedelta_seconds(self.run_every)
  23. return False, rem
  24. class crontab_parser(object):
  25. """Parser for crontab expressions. Any expression of the form 'groups' (see
  26. BNF grammar below) is accepted and expanded to a set of numbers. These
  27. numbers represent the units of time that the crontab needs to run on::
  28. digit :: '0'..'9'
  29. dow :: 'a'..'z'
  30. number :: digit+ | dow+
  31. steps :: number
  32. range :: number ( '-' number ) ?
  33. numspec :: '*' | range
  34. expr :: numspec ( '/' steps ) ?
  35. groups :: expr ( ',' expr ) *
  36. The parser is a general purpose one, useful for parsing hours, minutes and
  37. day_of_week expressions. Example usage::
  38. minutes = crontab_parser(60).parse("*/15") # yields [0,15,30,45]
  39. hours = crontab_parser(24).parse("*/4") # yields [0,4,8,12,16,20]
  40. day_of_week = crontab_parser(7).parse("*") # yields [0,1,2,3,4,5,6]
  41. """
  42. def __init__(self, max_=60):
  43. # define the grammar structure
  44. digits = "0123456789"
  45. star = Literal('*')
  46. number = Word(digits) | Word(alphas)
  47. steps = number
  48. range_ = number + Optional(Literal('-') + number)
  49. numspec = star | range_
  50. expr = Group(numspec) + Optional(Literal('/') + steps)
  51. extra_groups = ZeroOrMore(Literal(',') + expr)
  52. groups = expr + extra_groups + StringEnd()
  53. # define parse actions
  54. star.setParseAction(self._expand_star)
  55. number.setParseAction(self._expand_number)
  56. range_.setParseAction(self._expand_range)
  57. expr.setParseAction(self._filter_steps)
  58. extra_groups.setParseAction(self._ignore_comma)
  59. groups.setParseAction(self._join_to_set)
  60. self.max_ = max_
  61. self.parser = groups
  62. @staticmethod
  63. def _expand_number(toks):
  64. try:
  65. i = int(toks[0])
  66. except ValueError:
  67. try:
  68. i = weekday(toks[0])
  69. except KeyError:
  70. raise ValueError("Invalid weekday literal '%s'." % toks[0])
  71. return [i]
  72. @staticmethod
  73. def _expand_range(toks):
  74. if len(toks) > 1:
  75. return range(toks[0], int(toks[2])+1)
  76. else:
  77. return toks[0]
  78. def _expand_star(self, toks):
  79. return range(self.max_)
  80. @staticmethod
  81. def _filter_steps(toks):
  82. numbers = toks[0]
  83. if len(toks) > 1:
  84. steps = toks[2]
  85. return [n for n in numbers if n % steps == 0]
  86. else:
  87. return numbers
  88. @staticmethod
  89. def _ignore_comma(toks):
  90. return filter(lambda x: x != ',', toks)
  91. @staticmethod
  92. def _join_to_set(toks):
  93. return set(toks.asList())
  94. def parse(self, cronspec):
  95. return self.parser.parseString(cronspec).pop()
  96. class crontab(schedule):
  97. """A crontab can be used as the ``run_every`` value of a
  98. :class:`PeriodicTask` to add cron-like scheduling.
  99. Like a :manpage:`cron` job, you can specify units of time of when
  100. you would like the task to execute. It is a reasonably complete
  101. implementation of cron's features, so it should provide a fair
  102. degree of scheduling needs.
  103. You can specify a minute, an hour, and/or a day of the week in any
  104. of the following formats:
  105. .. attribute:: minute
  106. - A (list of) integers from 0-59 that represent the minutes of
  107. an hour of when execution should occur; or
  108. - A string representing a crontab pattern. This may get pretty
  109. advanced, like `minute="*/15"` (for every quarter) or
  110. `minute="1,13,30-45,50-59/2"`.
  111. .. attribute:: hour
  112. - A (list of) integers from 0-23 that represent the hours of
  113. a day of when execution should occur; or
  114. - A string representing a crontab pattern. This may get pretty
  115. advanced, like `hour="*/3"` (for every three hours) or
  116. `hour="0,8-17/2"` (at midnight, and every two hours during
  117. office hours).
  118. .. attribute:: day_of_week
  119. - A (list of) integers from 0-6, where Sunday = 0 and Saturday =
  120. 6, that represent the days of a week that execution should
  121. occur.
  122. - A string representing a crontab pattern. This may get pretty
  123. advanced, like `day_of_week="mon-fri"` (for weekdays only).
  124. (Beware that `day_of_week="*/2"` does not literally mean
  125. "every two days", but "every day that is divisible by two"!)
  126. """
  127. @staticmethod
  128. def _expand_cronspec(cronspec, max_):
  129. """Takes the given cronspec argument in one of the forms::
  130. int (like 7)
  131. basestring (like '3-5,*/15', '*', or 'monday')
  132. set (like set([0,15,30,45]))
  133. list (like [8-17])
  134. And convert it to an (expanded) set representing all time unit
  135. values on which the crontab triggers. Only in case of the base
  136. type being 'basestring', parsing occurs. (It is fast and
  137. happens only once for each crontab instance, so there is no
  138. significant performance overhead involved.)
  139. For the other base types, merely Python type conversions happen.
  140. The argument `max_` is needed to determine the expansion of '*'.
  141. """
  142. if isinstance(cronspec, int):
  143. result = set([cronspec])
  144. elif isinstance(cronspec, basestring):
  145. result = crontab_parser(max_).parse(cronspec)
  146. elif isinstance(cronspec, set):
  147. result = cronspec
  148. elif is_iterable(cronspec):
  149. result = set(cronspec)
  150. else:
  151. raise TypeError("Argument cronspec needs to be of any of the " + \
  152. "following types: int, basestring, or an iterable type. " + \
  153. "'%s' was given." % type(cronspec))
  154. # assure the result does not exceed the max
  155. for number in result:
  156. if number >= max_:
  157. raise ValueError("Invalid crontab pattern. Valid " + \
  158. "range is 0-%d. '%d' was found." % (max_, number))
  159. return result
  160. def __init__(self, minute='*', hour='*', day_of_week='*',
  161. nowfun=datetime.now):
  162. self.hour = self._expand_cronspec(hour, 24)
  163. self.minute = self._expand_cronspec(minute, 60)
  164. self.day_of_week = self._expand_cronspec(day_of_week, 7)
  165. self.nowfun = nowfun
  166. def remaining_estimate(self, last_run_at):
  167. # remaining_estimate controls the frequency of scheduler
  168. # ticks. The scheduler needs to wake up every second in this case.
  169. return 1
  170. def is_due(self, last_run_at):
  171. now = self.nowfun()
  172. last = now - last_run_at
  173. due, when = False, 1
  174. if last.days > 0 or last.seconds > 60:
  175. due = now.isoweekday() % 7 in self.day_of_week and \
  176. now.hour in self.hour and \
  177. now.minute in self.minute
  178. return due, when