schedules.py 20 KB

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