schedules.py 19 KB

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