schedules.py 21 KB

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