schedules.py 13 KB

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