schedules.py 7.8 KB

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