schedules.py 21 KB

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