schedules.py 21 KB

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