schedules.py 11 KB

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