schedules.py 19 KB

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