schedules.py 19 KB

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