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