schedules.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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 datetime, 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. from .datastructures import AttributeDict
  19. class ParseException(Exception):
  20. """Raised by crontab_parser when the input can't be parsed."""
  21. class schedule(object):
  22. relative = False
  23. def __init__(self, run_every=None, relative=False, nowfun=None):
  24. self.run_every = maybe_timedelta(run_every)
  25. self.relative = relative
  26. self.nowfun = nowfun
  27. def now(self):
  28. return (self.nowfun or current_app.now)()
  29. def remaining_estimate(self, last_run_at):
  30. """Returns when the periodic task should run next as a timedelta."""
  31. return remaining(last_run_at, self.run_every, relative=self.relative,
  32. now=self.now())
  33. def is_due(self, last_run_at):
  34. """Returns tuple of two items `(is_due, next_time_to_run)`,
  35. where next time to run is in seconds.
  36. e.g.
  37. * `(True, 20)`, means the task should be run now, and the next
  38. time to run is in 20 seconds.
  39. * `(False, 12)`, means the task should be run in 12 seconds.
  40. You can override this to decide the interval at runtime,
  41. but keep in mind the value of :setting:`CELERYBEAT_MAX_LOOP_INTERVAL`,
  42. which decides the maximum number of seconds celerybeat can sleep
  43. between re-checking the periodic task intervals. So if you
  44. dynamically change the next run at value, and the max interval is
  45. set to 5 minutes, it will take 5 minutes for the change to take
  46. effect, so you may consider lowering the value of
  47. :setting:`CELERYBEAT_MAX_LOOP_INTERVAL` if responsiveness is of
  48. importance to you.
  49. .. admonition:: Scheduler max interval variance
  50. The default max loop interval may vary for different schedulers.
  51. For the default scheduler the value is 5 minutes, but for e.g.
  52. the django-celery database scheduler the value is 5 seconds.
  53. """
  54. rem_delta = self.remaining_estimate(last_run_at)
  55. rem = timedelta_seconds(rem_delta)
  56. if rem == 0:
  57. return True, self.seconds
  58. return False, rem
  59. def __repr__(self):
  60. return "<freq: %s>" % self.human_seconds
  61. def __eq__(self, other):
  62. if isinstance(other, schedule):
  63. return self.run_every == other.run_every
  64. return self.run_every == other
  65. @property
  66. def seconds(self):
  67. return timedelta_seconds(self.run_every)
  68. @property
  69. def human_seconds(self):
  70. return humanize_seconds(self.seconds)
  71. class crontab_parser(object):
  72. """Parser for crontab expressions. Any expression of the form 'groups'
  73. (see BNF grammar below) is accepted and expanded to a set of numbers.
  74. These numbers represent the units of time that the crontab needs to
  75. run on::
  76. digit :: '0'..'9'
  77. dow :: 'a'..'z'
  78. number :: digit+ | dow+
  79. steps :: number
  80. range :: number ( '-' number ) ?
  81. numspec :: '*' | range
  82. expr :: numspec ( '/' steps ) ?
  83. groups :: expr ( ',' expr ) *
  84. The parser is a general purpose one, useful for parsing hours, minutes and
  85. day_of_week expressions. Example usage::
  86. >>> minutes = crontab_parser(60).parse("*/15")
  87. [0, 15, 30, 45]
  88. >>> hours = crontab_parser(24).parse("*/4")
  89. [0, 4, 8, 12, 16, 20]
  90. >>> day_of_week = crontab_parser(7).parse("*")
  91. [0, 1, 2, 3, 4, 5, 6]
  92. It can also parse day_of_month and month_of_year expressions if initialized
  93. with an minimum of 1. Example usage::
  94. >>> days_of_month = crontab_parser(31, 1).parse("*/3")
  95. [1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31]
  96. >>> months_of_year = crontab_parser(12, 1).parse("*/2")
  97. [1, 3, 5, 7, 9, 11]
  98. >>> months_of_year = crontab_parser(12, 1).parse("2-12/2")
  99. [2, 4, 6, 8, 10, 12]
  100. The maximum possible expanded value returned is found by the formula::
  101. max_ + min_ - 1
  102. """
  103. ParseException = ParseException
  104. _range = r'(\w+?)-(\w+)'
  105. _steps = r'/(\w+)?'
  106. _star = r'\*'
  107. def __init__(self, max_=60, min_=0):
  108. self.max_ = max_
  109. self.min_ = min_
  110. self.pats = (
  111. (re.compile(self._range + self._steps), self._range_steps),
  112. (re.compile(self._range), self._expand_range),
  113. (re.compile(self._star + self._steps), self._star_steps),
  114. (re.compile('^' + self._star + '$'), self._expand_star))
  115. def parse(self, spec):
  116. acc = set()
  117. for part in spec.split(','):
  118. if not part:
  119. raise self.ParseException("empty part")
  120. acc |= set(self._parse_part(part))
  121. return acc
  122. def _parse_part(self, part):
  123. for regex, handler in self.pats:
  124. m = regex.match(part)
  125. if m:
  126. return handler(m.groups())
  127. return self._expand_range((part, ))
  128. def _expand_range(self, toks):
  129. fr = self._expand_number(toks[0])
  130. if len(toks) > 1:
  131. to = self._expand_number(toks[1])
  132. return range(fr, min(to + 1, self.max_ + 1))
  133. return [fr]
  134. def _range_steps(self, toks):
  135. if len(toks) != 3 or not toks[2]:
  136. raise self.ParseException("empty filter")
  137. return self._expand_range(toks[:2])[::int(toks[2])]
  138. def _star_steps(self, toks):
  139. if not toks or not toks[0]:
  140. raise self.ParseException("empty filter")
  141. return self._expand_star()[::int(toks[0])]
  142. def _expand_star(self, *args):
  143. return range(self.min_, self.max_ + self.min_)
  144. def _expand_number(self, s):
  145. if isinstance(s, basestring) and s[0] == '-':
  146. raise self.ParseException("negative numbers not supported")
  147. try:
  148. i = int(s)
  149. except ValueError:
  150. try:
  151. i = weekday(s)
  152. except KeyError:
  153. raise ValueError("Invalid weekday literal '%s'." % s)
  154. if i < self.min_:
  155. raise ValueError("Invalid beginning range - %s < %s." %
  156. (i, self.min_))
  157. return i
  158. class crontab(schedule):
  159. """A crontab can be used as the `run_every` value of a
  160. :class:`PeriodicTask` to add cron-like scheduling.
  161. Like a :manpage:`cron` job, you can specify units of time of when
  162. you would like the task to execute. It is a reasonably complete
  163. implementation of cron's features, so it should provide a fair
  164. degree of scheduling needs.
  165. You can specify a minute, an hour, a day of the week, a day of the
  166. month, and/or a month in the year in any of the following formats:
  167. .. attribute:: minute
  168. - A (list of) integers from 0-59 that represent the minutes of
  169. an hour of when execution should occur; or
  170. - A string representing a crontab pattern. This may get pretty
  171. advanced, like `minute="*/15"` (for every quarter) or
  172. `minute="1,13,30-45,50-59/2"`.
  173. .. attribute:: hour
  174. - A (list of) integers from 0-23 that represent the hours of
  175. a day of when execution should occur; or
  176. - A string representing a crontab pattern. This may get pretty
  177. advanced, like `hour="*/3"` (for every three hours) or
  178. `hour="0,8-17/2"` (at midnight, and every two hours during
  179. office hours).
  180. .. attribute:: day_of_week
  181. - A (list of) integers from 0-6, where Sunday = 0 and Saturday =
  182. 6, that represent the days of a week that execution should
  183. occur.
  184. - A string representing a crontab pattern. This may get pretty
  185. advanced, like `day_of_week="mon-fri"` (for weekdays only).
  186. (Beware that `day_of_week="*/2"` does not literally mean
  187. "every two days", but "every day that is divisible by two"!)
  188. .. attribute:: day_of_month
  189. - A (list of) integers from 1-31 that represents the days of the
  190. month that execution should occur.
  191. - A string representing a crontab pattern. This may get pretty
  192. advanced, such as `day_of_month="2-30/3"` (for every even
  193. numbered day) or `day_of_month="1-7,15-21"` (for the first and
  194. third weeks of the month).
  195. .. attribute:: month_of_year
  196. - A (list of) integers from 1-12 that represents the months of
  197. the year during which execution can occur.
  198. - A string representing a crontab pattern. This may get pretty
  199. advanced, such as `month_of_year="*/3"` (for the first month
  200. of every quarter) or `month_of_year="2-12/2"` (for every even
  201. numbered month).
  202. It is important to realize that any day on which execution should
  203. occur must be represented by entries in all three of the day and
  204. month attributes. For example, if `day_of_week` is 0 and `day_of_month`
  205. is every seventh day, only months that begin on Sunday and are also
  206. in the `month_of_year` attribute will have execution events. Or,
  207. `day_of_week` is 1 and `day_of_month` is "1-7,15-21" means every
  208. first and third monday of every month present in `month_of_year`.
  209. """
  210. @staticmethod
  211. def _expand_cronspec(cronspec, max_, min_=0):
  212. """Takes the given cronspec argument in one of the forms::
  213. int (like 7)
  214. basestring (like '3-5,*/15', '*', or 'monday')
  215. set (like set([0,15,30,45]))
  216. list (like [8-17])
  217. And convert it to an (expanded) set representing all time unit
  218. values on which the crontab triggers. Only in case of the base
  219. type being 'basestring', parsing occurs. (It is fast and
  220. happens only once for each crontab instance, so there is no
  221. significant performance overhead involved.)
  222. For the other base types, merely Python type conversions happen.
  223. The argument `max_` is needed to determine the expansion of '*'
  224. and ranges.
  225. The argument `min_` is needed to determine the expansion of '*'
  226. and ranges for 1-based cronspecs, such as day of month or month
  227. of year. The default is sufficient for minute, hour, and day of
  228. week.
  229. """
  230. if isinstance(cronspec, int):
  231. result = set([cronspec])
  232. elif isinstance(cronspec, basestring):
  233. result = crontab_parser(max_, min_).parse(cronspec)
  234. elif isinstance(cronspec, set):
  235. result = cronspec
  236. elif is_iterable(cronspec):
  237. result = set(cronspec)
  238. else:
  239. raise TypeError(
  240. "Argument cronspec needs to be of any of the "
  241. "following types: int, basestring, or an iterable type. "
  242. "'%s' was given." % type(cronspec))
  243. # assure the result does not preceed the min or exceed the max
  244. for number in result:
  245. if number >= max_ + min_ or number < min_:
  246. raise ValueError(
  247. "Invalid crontab pattern. Valid "
  248. "range is %d-%d. '%d' was found." %
  249. (min_, max_ - 1 + min_, number))
  250. return result
  251. def _delta_to_next(self, last_run_at, next_hour, next_minute):
  252. """
  253. Takes a datetime of last run, next minute and hour, and
  254. returns a relativedelta for the next scheduled day and time.
  255. Only called when day_of_month and/or month_of_year cronspec
  256. is specified to further limit scheduled task execution.
  257. """
  258. from bisect import bisect, bisect_left
  259. datedata = AttributeDict(year=last_run_at.year)
  260. days_of_month = sorted(self.day_of_month)
  261. months_of_year = sorted(self.month_of_year)
  262. def day_out_of_range(year, month, day):
  263. try:
  264. datetime(year=year, month=month, day=day)
  265. except ValueError:
  266. return True
  267. return False
  268. def roll_over():
  269. while 1:
  270. flag = (datedata.dom == len(days_of_month) or
  271. day_out_of_range(datedata.year,
  272. months_of_year[datedata.moy],
  273. days_of_month[datedata.dom]))
  274. if flag:
  275. datedata.dom = 0
  276. datedata.moy += 1
  277. if datedata.moy == len(months_of_year):
  278. datedata.moy = 0
  279. datedata.year += 1
  280. else:
  281. break
  282. if last_run_at.month in self.month_of_year:
  283. datedata.dom = bisect(days_of_month, last_run_at.day)
  284. datedata.moy = bisect_left(months_of_year, last_run_at.month)
  285. else:
  286. datedata.dom = 0
  287. datedata.moy = bisect(months_of_year, last_run_at.month)
  288. roll_over()
  289. while not (datetime(year=datedata.year,
  290. month=months_of_year[datedata.moy],
  291. day=days_of_month[datedata.dom]
  292. ).isoweekday() % 7
  293. ) in self.day_of_week:
  294. datedata.dom += 1
  295. roll_over()
  296. return relativedelta(year=datedata.year,
  297. month=months_of_year[datedata.moy],
  298. day=days_of_month[datedata.dom],
  299. hour=next_hour,
  300. minute=next_minute,
  301. second=0,
  302. microsecond=0)
  303. def __init__(self, minute='*', hour='*', day_of_week='*',
  304. day_of_month='*', month_of_year='*', nowfun=None):
  305. self._orig_minute = minute
  306. self._orig_hour = hour
  307. self._orig_day_of_week = day_of_week
  308. self._orig_day_of_month = day_of_month
  309. self._orig_month_of_year = month_of_year
  310. self.hour = self._expand_cronspec(hour, 24)
  311. self.minute = self._expand_cronspec(minute, 60)
  312. self.day_of_week = self._expand_cronspec(day_of_week, 7)
  313. self.day_of_month = self._expand_cronspec(day_of_month, 31, 1)
  314. self.month_of_year = self._expand_cronspec(month_of_year, 12, 1)
  315. self.nowfun = nowfun or current_app.now
  316. def __repr__(self):
  317. return ("<crontab: %s %s %s %s %s (m/h/d/dM/MY)>" %
  318. (self._orig_minute or "*",
  319. self._orig_hour or "*",
  320. self._orig_day_of_week or "*",
  321. self._orig_day_of_month or "*",
  322. self._orig_month_of_year or "*"))
  323. def __reduce__(self):
  324. return (self.__class__, (self._orig_minute,
  325. self._orig_hour,
  326. self._orig_day_of_week,
  327. self._orig_day_of_month,
  328. self._orig_month_of_year), None)
  329. def remaining_estimate(self, last_run_at):
  330. """Returns when the periodic task should run next as a timedelta."""
  331. dow_num = last_run_at.isoweekday() % 7 # Sunday is day 0, not day 7
  332. execute_this_date = (last_run_at.month in self.month_of_year and
  333. last_run_at.day in self.day_of_month and
  334. dow_num in self.day_of_week)
  335. execute_this_hour = (execute_this_date and
  336. last_run_at.hour in self.hour and
  337. last_run_at.minute < max(self.minute))
  338. if execute_this_hour:
  339. next_minute = min(minute for minute in self.minute
  340. if minute > last_run_at.minute)
  341. delta = relativedelta(minute=next_minute,
  342. second=0,
  343. microsecond=0)
  344. else:
  345. next_minute = min(self.minute)
  346. execute_today = (execute_this_date and
  347. last_run_at.hour < max(self.hour))
  348. if execute_today:
  349. next_hour = min(hour for hour in self.hour
  350. if hour > last_run_at.hour)
  351. delta = relativedelta(hour=next_hour,
  352. minute=next_minute,
  353. second=0,
  354. microsecond=0)
  355. else:
  356. next_hour = min(self.hour)
  357. all_dom_moy = (self._orig_day_of_month == "*" and
  358. self._orig_month_of_year == "*")
  359. if all_dom_moy:
  360. next_day = min([day for day in self.day_of_week
  361. if day > dow_num] or
  362. self.day_of_week)
  363. add_week = next_day == dow_num
  364. delta = relativedelta(weeks=add_week and 1 or 0,
  365. weekday=(next_day - 1) % 7,
  366. hour=next_hour,
  367. minute=next_minute,
  368. second=0,
  369. microsecond=0)
  370. else:
  371. delta = self._delta_to_next(last_run_at,
  372. next_hour, next_minute)
  373. return remaining(last_run_at, delta, now=self.nowfun())
  374. def is_due(self, last_run_at):
  375. """Returns tuple of two items `(is_due, next_time_to_run)`,
  376. where next time to run is in seconds.
  377. See :meth:`celery.schedules.schedule.is_due` for more information.
  378. """
  379. rem_delta = self.remaining_estimate(last_run_at)
  380. rem = timedelta_seconds(rem_delta)
  381. due = rem == 0
  382. if due:
  383. rem_delta = self.remaining_estimate(last_run_at=self.nowfun())
  384. rem = timedelta_seconds(rem_delta)
  385. return due, rem
  386. def __eq__(self, other):
  387. if isinstance(other, crontab):
  388. return (other.month_of_year == self.month_of_year and
  389. other.day_of_month == self.day_of_month and
  390. other.day_of_week == self.day_of_week and
  391. other.hour == self.hour and
  392. other.minute == self.minute)
  393. return other is self
  394. def maybe_schedule(s, relative=False):
  395. if isinstance(s, int):
  396. s = timedelta(seconds=s)
  397. if isinstance(s, timedelta):
  398. return schedule(s, relative)
  399. return s