schedules.py 9.0 KB

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