schedules.py 12 KB

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