schedules.py 13 KB

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