schedules.py 20 KB

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