schedules.py 12 KB

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