schedules.py 12 KB

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