schedules.py 19 KB

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