schedules.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. # -*- coding: utf-8 -*-
  2. """Schedules define the intervals at which periodic tasks run."""
  3. from __future__ import absolute_import, unicode_literals
  4. import numbers
  5. import re
  6. from bisect import bisect, bisect_left
  7. from collections import Iterable, namedtuple
  8. from datetime import datetime, timedelta
  9. from kombu.utils.objects import cached_property
  10. from . import current_app
  11. from .five import python_2_unicode_compatible, range, string_t
  12. from .utils.collections import AttributeDict
  13. from .utils.time import (
  14. weekday, maybe_timedelta, remaining, humanize_seconds,
  15. timezone, maybe_make_aware, ffwd, localize
  16. )
  17. __all__ = [
  18. 'ParseException', 'schedule', 'crontab', 'crontab_parser',
  19. 'maybe_schedule', 'solar',
  20. ]
  21. schedstate = namedtuple('schedstate', ('is_due', 'next'))
  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. SOLAR_INVALID_LATITUDE = """\
  35. Argument latitude {lat} is invalid, must be between -90 and 90.\
  36. """
  37. SOLAR_INVALID_LONGITUDE = """\
  38. Argument longitude {lon} is invalid, must be between -180 and 180.\
  39. """
  40. SOLAR_INVALID_EVENT = """\
  41. Argument event "{event}" is invalid, must be one of {all_events}.\
  42. """
  43. def cronfield(s):
  44. return '*' if s is None else s
  45. class ParseException(Exception):
  46. """Raised by :class:`crontab_parser` when the input can't be parsed."""
  47. class BaseSchedule(object):
  48. def __init__(self, nowfun=None, app=None):
  49. self.nowfun = nowfun
  50. self._app = app
  51. def now(self):
  52. return (self.nowfun or self.app.now)()
  53. def remaining_estimate(self, last_run_at):
  54. raise NotImplementedError()
  55. def is_due(self, last_run_at):
  56. raise NotImplementedError()
  57. def maybe_make_aware(self, dt):
  58. return maybe_make_aware(dt, self.tz)
  59. @property
  60. def app(self):
  61. return self._app or current_app._get_current_object()
  62. @app.setter # noqa
  63. def app(self, app):
  64. self._app = app
  65. @cached_property
  66. def tz(self):
  67. return self.app.timezone
  68. @cached_property
  69. def utc_enabled(self):
  70. return self.app.conf.enable_utc
  71. def to_local(self, dt):
  72. if not self.utc_enabled:
  73. return timezone.to_local_fallback(dt)
  74. return dt
  75. @python_2_unicode_compatible
  76. class schedule(BaseSchedule):
  77. """Schedule for periodic task.
  78. Arguments:
  79. run_every (float, ~datetime.timedelta): Time interval.
  80. relative (bool): If set to True the run time will be rounded to the
  81. resolution of the interval.
  82. nowfun (Callable): Function returning the current date and time
  83. (class:`~datetime.datetime`).
  84. app (~@Celery): Celery app instance.
  85. """
  86. relative = False
  87. def __init__(self, run_every=None, relative=False, nowfun=None, app=None):
  88. self.run_every = maybe_timedelta(run_every)
  89. self.relative = relative
  90. super(schedule, self).__init__(nowfun=nowfun, app=app)
  91. def remaining_estimate(self, last_run_at):
  92. return remaining(
  93. self.maybe_make_aware(last_run_at), self.run_every,
  94. self.maybe_make_aware(self.now()), self.relative,
  95. )
  96. def is_due(self, last_run_at):
  97. """Return tuple of ``(is_due, next_time_to_check)``.
  98. Notes:
  99. - next time to check is in seconds.
  100. - ``(True, 20)``, means the task should be run now, and the next
  101. time to check is in 20 seconds.
  102. - ``(False, 12.3)``, means the task is not due, but that the
  103. scheduler should check again in 12.3 seconds.
  104. The next time to check is used to save energy/CPU cycles,
  105. it does not need to be accurate but will influence the precision
  106. of your schedule. You must also keep in mind
  107. the value of :setting:`beat_max_loop_interval`,
  108. that decides the maximum number of seconds the scheduler can
  109. sleep between re-checking the periodic task intervals. So if you
  110. have a task that changes schedule at run-time then your next_run_at
  111. check will decide how long it will take before a change to the
  112. schedule takes effect. The max loop interval takes precedence
  113. over the next check at value returned.
  114. .. admonition:: Scheduler max interval variance
  115. The default max loop interval may vary for different schedulers.
  116. For the default scheduler the value is 5 minutes, but for example
  117. the :pypi:`django-celery-beat` database scheduler the value
  118. is 5 seconds.
  119. """
  120. last_run_at = self.maybe_make_aware(last_run_at)
  121. rem_delta = self.remaining_estimate(last_run_at)
  122. remaining_s = max(rem_delta.total_seconds(), 0)
  123. if remaining_s == 0:
  124. return schedstate(is_due=True, next=self.seconds)
  125. return schedstate(is_due=False, next=remaining_s)
  126. def __repr__(self):
  127. return '<freq: {0.human_seconds}>'.format(self)
  128. def __eq__(self, other):
  129. if isinstance(other, schedule):
  130. return self.run_every == other.run_every
  131. return self.run_every == other
  132. def __ne__(self, other):
  133. return not self.__eq__(other)
  134. def __reduce__(self):
  135. return self.__class__, (self.run_every, self.relative, self.nowfun)
  136. @property
  137. def seconds(self):
  138. return max(self.run_every.total_seconds(), 0)
  139. @property
  140. def human_seconds(self):
  141. return humanize_seconds(self.seconds)
  142. class crontab_parser(object):
  143. """Parser for Crontab expressions.
  144. Any expression of the form 'groups'
  145. (see BNF grammar below) is accepted and expanded to a set of numbers.
  146. These numbers represent the units of time that the Crontab needs to
  147. run on:
  148. .. code-block:: bnf
  149. digit :: '0'..'9'
  150. dow :: 'a'..'z'
  151. number :: digit+ | dow+
  152. steps :: number
  153. range :: number ( '-' number ) ?
  154. numspec :: '*' | range
  155. expr :: numspec ( '/' steps ) ?
  156. groups :: expr ( ',' expr ) *
  157. The parser is a general purpose one, useful for parsing hours, minutes and
  158. day of week expressions. Example usage:
  159. .. code-block:: pycon
  160. >>> minutes = crontab_parser(60).parse('*/15')
  161. [0, 15, 30, 45]
  162. >>> hours = crontab_parser(24).parse('*/4')
  163. [0, 4, 8, 12, 16, 20]
  164. >>> day_of_week = crontab_parser(7).parse('*')
  165. [0, 1, 2, 3, 4, 5, 6]
  166. It can also parse day of month and month of year expressions if initialized
  167. with a minimum of 1. Example usage:
  168. .. code-block:: pycon
  169. >>> days_of_month = crontab_parser(31, 1).parse('*/3')
  170. [1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31]
  171. >>> months_of_year = crontab_parser(12, 1).parse('*/2')
  172. [1, 3, 5, 7, 9, 11]
  173. >>> months_of_year = crontab_parser(12, 1).parse('2-12/2')
  174. [2, 4, 6, 8, 10, 12]
  175. The maximum possible expanded value returned is found by the formula:
  176. :math:`max_ + min_ - 1`
  177. """
  178. ParseException = ParseException
  179. _range = r'(\w+?)-(\w+)'
  180. _steps = r'/(\w+)?'
  181. _star = r'\*'
  182. def __init__(self, max_=60, min_=0):
  183. self.max_ = max_
  184. self.min_ = min_
  185. self.pats = (
  186. (re.compile(self._range + self._steps), self._range_steps),
  187. (re.compile(self._range), self._expand_range),
  188. (re.compile(self._star + self._steps), self._star_steps),
  189. (re.compile('^' + self._star + '$'), self._expand_star),
  190. )
  191. def parse(self, spec):
  192. acc = set()
  193. for part in spec.split(','):
  194. if not part:
  195. raise self.ParseException('empty part')
  196. acc |= set(self._parse_part(part))
  197. return acc
  198. def _parse_part(self, part):
  199. for regex, handler in self.pats:
  200. m = regex.match(part)
  201. if m:
  202. return handler(m.groups())
  203. return self._expand_range((part,))
  204. def _expand_range(self, toks):
  205. fr = self._expand_number(toks[0])
  206. if len(toks) > 1:
  207. to = self._expand_number(toks[1])
  208. if to < fr: # Wrap around max_ if necessary
  209. return (list(range(fr, self.min_ + self.max_)) +
  210. list(range(self.min_, to + 1)))
  211. return list(range(fr, to + 1))
  212. return [fr]
  213. def _range_steps(self, toks):
  214. if len(toks) != 3 or not toks[2]:
  215. raise self.ParseException('empty filter')
  216. return self._expand_range(toks[:2])[::int(toks[2])]
  217. def _star_steps(self, toks):
  218. if not toks or not toks[0]:
  219. raise self.ParseException('empty filter')
  220. return self._expand_star()[::int(toks[0])]
  221. def _expand_star(self, *args):
  222. return list(range(self.min_, self.max_ + self.min_))
  223. def _expand_number(self, s):
  224. if isinstance(s, string_t) and s[0] == '-':
  225. raise self.ParseException('negative numbers not supported')
  226. try:
  227. i = int(s)
  228. except ValueError:
  229. try:
  230. i = weekday(s)
  231. except KeyError:
  232. raise ValueError('Invalid weekday literal {0!r}.'.format(s))
  233. max_val = self.min_ + self.max_ - 1
  234. if i > max_val:
  235. raise ValueError(
  236. 'Invalid end range: {0} > {1}.'.format(i, max_val))
  237. if i < self.min_:
  238. raise ValueError(
  239. 'Invalid beginning range: {0} < {1}.'.format(i, self.min_))
  240. return i
  241. @python_2_unicode_compatible
  242. class crontab(BaseSchedule):
  243. """Crontab schedule.
  244. A Crontab can be used as the ``run_every`` value of a
  245. periodic task entry to add :manpage:`crontab(5)`-like scheduling.
  246. Like a :manpage:`cron(5)`-job, you can specify units of time of when
  247. you'd like the task to execute. It's a reasonably complete
  248. implementation of :command:`cron`'s features, so it should provide a fair
  249. degree of scheduling needs.
  250. You can specify a minute, an hour, a day of the week, a day of the
  251. month, and/or a month in the year in any of the following formats:
  252. .. attribute:: minute
  253. - A (list of) integers from 0-59 that represent the minutes of
  254. an hour of when execution should occur; or
  255. - A string representing a Crontab pattern. This may get pretty
  256. advanced, like ``minute='*/15'`` (for every quarter) or
  257. ``minute='1,13,30-45,50-59/2'``.
  258. .. attribute:: hour
  259. - A (list of) integers from 0-23 that represent the hours of
  260. a day of when execution should occur; or
  261. - A string representing a Crontab pattern. This may get pretty
  262. advanced, like ``hour='*/3'`` (for every three hours) or
  263. ``hour='0,8-17/2'`` (at midnight, and every two hours during
  264. office hours).
  265. .. attribute:: day_of_week
  266. - A (list of) integers from 0-6, where Sunday = 0 and Saturday =
  267. 6, that represent the days of a week that execution should
  268. occur.
  269. - A string representing a Crontab pattern. This may get pretty
  270. advanced, like ``day_of_week='mon-fri'`` (for weekdays only).
  271. (Beware that ``day_of_week='*/2'`` does not literally mean
  272. 'every two days', but 'every day that is divisible by two'!)
  273. .. attribute:: day_of_month
  274. - A (list of) integers from 1-31 that represents the days of the
  275. month that execution should occur.
  276. - A string representing a Crontab pattern. This may get pretty
  277. advanced, such as ``day_of_month='2-30/3'`` (for every even
  278. numbered day) or ``day_of_month='1-7,15-21'`` (for the first and
  279. third weeks of the month).
  280. .. attribute:: month_of_year
  281. - A (list of) integers from 1-12 that represents the months of
  282. the year during which execution can occur.
  283. - A string representing a Crontab pattern. This may get pretty
  284. advanced, such as ``month_of_year='*/3'`` (for the first month
  285. of every quarter) or ``month_of_year='2-12/2'`` (for every even
  286. numbered month).
  287. .. attribute:: nowfun
  288. Function returning the current date and time
  289. (:class:`~datetime.datetime`).
  290. .. attribute:: app
  291. The Celery app instance.
  292. It's important to realize that any day on which execution should
  293. occur must be represented by entries in all three of the day and
  294. month attributes. For example, if ``day_of_week`` is 0 and
  295. ``day_of_month`` is every seventh day, only months that begin
  296. on Sunday and are also in the ``month_of_year`` attribute will have
  297. execution events. Or, ``day_of_week`` is 1 and ``day_of_month``
  298. is '1-7,15-21' means every first and third Monday of every month
  299. present in ``month_of_year``.
  300. """
  301. def __init__(self, minute='*', hour='*', day_of_week='*',
  302. day_of_month='*', month_of_year='*', **kwargs):
  303. self._orig_minute = cronfield(minute)
  304. self._orig_hour = cronfield(hour)
  305. self._orig_day_of_week = cronfield(day_of_week)
  306. self._orig_day_of_month = cronfield(day_of_month)
  307. self._orig_month_of_year = cronfield(month_of_year)
  308. self.hour = self._expand_cronspec(hour, 24)
  309. self.minute = self._expand_cronspec(minute, 60)
  310. self.day_of_week = self._expand_cronspec(day_of_week, 7)
  311. self.day_of_month = self._expand_cronspec(day_of_month, 31, 1)
  312. self.month_of_year = self._expand_cronspec(month_of_year, 12, 1)
  313. super(crontab, self).__init__(**kwargs)
  314. @staticmethod
  315. def _expand_cronspec(cronspec, max_, min_=0):
  316. """Expand cron specification.
  317. Takes the given cronspec argument in one of the forms:
  318. .. code-block:: text
  319. int (like 7)
  320. str (like '3-5,*/15', '*', or 'monday')
  321. set (like {0,15,30,45}
  322. list (like [8-17])
  323. And convert it to an (expanded) set representing all time unit
  324. values on which the Crontab triggers. Only in case of the base
  325. type being :class:`str`, parsing occurs. (It's fast and
  326. happens only once for each Crontab instance, so there's no
  327. significant performance overhead involved.)
  328. For the other base types, merely Python type conversions happen.
  329. The argument ``max_`` is needed to determine the expansion of
  330. ``*`` and ranges. The argument ``min_`` is needed to determine
  331. the expansion of ``*`` and ranges for 1-based cronspecs, such as
  332. day of month or month of year. The default is sufficient for minute,
  333. hour, and day of week.
  334. """
  335. if isinstance(cronspec, numbers.Integral):
  336. result = {cronspec}
  337. elif isinstance(cronspec, string_t):
  338. result = crontab_parser(max_, min_).parse(cronspec)
  339. elif isinstance(cronspec, set):
  340. result = cronspec
  341. elif isinstance(cronspec, Iterable):
  342. result = set(cronspec)
  343. else:
  344. raise TypeError(CRON_INVALID_TYPE.format(type=type(cronspec)))
  345. # assure the result does not preceed the min or exceed the max
  346. for number in result:
  347. if number >= max_ + min_ or number < min_:
  348. raise ValueError(CRON_PATTERN_INVALID.format(
  349. min=min_, max=max_ - 1 + min_, value=number))
  350. return result
  351. def _delta_to_next(self, last_run_at, next_hour, next_minute):
  352. """Find next delta.
  353. Takes a :class:`~datetime.datetime` of last run, next minute and hour,
  354. and returns a :class:`~celery.utils.time.ffwd` for the next
  355. scheduled day and time.
  356. Only called when ``day_of_month`` and/or ``month_of_year``
  357. cronspec is specified to further limit scheduled task execution.
  358. """
  359. datedata = AttributeDict(year=last_run_at.year)
  360. days_of_month = sorted(self.day_of_month)
  361. months_of_year = sorted(self.month_of_year)
  362. def day_out_of_range(year, month, day):
  363. try:
  364. datetime(year=year, month=month, day=day)
  365. except ValueError:
  366. return True
  367. return False
  368. def roll_over():
  369. for _ in range(2000):
  370. flag = (datedata.dom == len(days_of_month) or
  371. day_out_of_range(datedata.year,
  372. months_of_year[datedata.moy],
  373. days_of_month[datedata.dom]) or
  374. (self.maybe_make_aware(datetime(datedata.year,
  375. months_of_year[datedata.moy],
  376. days_of_month[datedata.dom])) < last_run_at))
  377. if flag:
  378. datedata.dom = 0
  379. datedata.moy += 1
  380. if datedata.moy == len(months_of_year):
  381. datedata.moy = 0
  382. datedata.year += 1
  383. else:
  384. break
  385. else:
  386. # Tried 2000 times, we're most likely in an infinite loop
  387. raise RuntimeError('unable to rollover, '
  388. 'time specification is probably invalid')
  389. if last_run_at.month in self.month_of_year:
  390. datedata.dom = bisect(days_of_month, last_run_at.day)
  391. datedata.moy = bisect_left(months_of_year, last_run_at.month)
  392. else:
  393. datedata.dom = 0
  394. datedata.moy = bisect(months_of_year, last_run_at.month)
  395. if datedata.moy == len(months_of_year):
  396. datedata.moy = 0
  397. roll_over()
  398. while 1:
  399. th = datetime(year=datedata.year,
  400. month=months_of_year[datedata.moy],
  401. day=days_of_month[datedata.dom])
  402. if th.isoweekday() % 7 in self.day_of_week:
  403. break
  404. datedata.dom += 1
  405. roll_over()
  406. return ffwd(year=datedata.year,
  407. month=months_of_year[datedata.moy],
  408. day=days_of_month[datedata.dom],
  409. hour=next_hour,
  410. minute=next_minute,
  411. second=0,
  412. microsecond=0)
  413. def __repr__(self):
  414. return CRON_REPR.format(self)
  415. def __reduce__(self):
  416. return (self.__class__, (self._orig_minute,
  417. self._orig_hour,
  418. self._orig_day_of_week,
  419. self._orig_day_of_month,
  420. self._orig_month_of_year), None)
  421. def remaining_delta(self, last_run_at, tz=None, ffwd=ffwd):
  422. # pylint: disable=redefined-outer-name
  423. # caching global ffwd
  424. tz = tz or self.tz
  425. last_run_at = self.maybe_make_aware(last_run_at)
  426. now = self.maybe_make_aware(self.now())
  427. dow_num = last_run_at.isoweekday() % 7 # Sunday is day 0, not day 7
  428. execute_this_date = (
  429. last_run_at.month in self.month_of_year and
  430. last_run_at.day in self.day_of_month and
  431. dow_num in self.day_of_week
  432. )
  433. execute_this_hour = (
  434. execute_this_date and
  435. last_run_at.day == now.day and
  436. last_run_at.month == now.month and
  437. last_run_at.year == now.year and
  438. last_run_at.hour in self.hour and
  439. last_run_at.minute < max(self.minute)
  440. )
  441. if execute_this_hour:
  442. next_minute = min(minute for minute in self.minute
  443. if minute > last_run_at.minute)
  444. delta = ffwd(minute=next_minute, second=0, microsecond=0)
  445. else:
  446. next_minute = min(self.minute)
  447. execute_today = (execute_this_date and
  448. last_run_at.hour < max(self.hour))
  449. if execute_today:
  450. next_hour = min(hour for hour in self.hour
  451. if hour > last_run_at.hour)
  452. delta = ffwd(hour=next_hour, minute=next_minute,
  453. second=0, microsecond=0)
  454. else:
  455. next_hour = min(self.hour)
  456. all_dom_moy = (self._orig_day_of_month == '*' and
  457. self._orig_month_of_year == '*')
  458. if all_dom_moy:
  459. next_day = min([day for day in self.day_of_week
  460. if day > dow_num] or self.day_of_week)
  461. add_week = next_day == dow_num
  462. delta = ffwd(
  463. weeks=add_week and 1 or 0,
  464. weekday=(next_day - 1) % 7,
  465. hour=next_hour,
  466. minute=next_minute,
  467. second=0,
  468. microsecond=0,
  469. )
  470. else:
  471. delta = self._delta_to_next(last_run_at,
  472. next_hour, next_minute)
  473. return self.to_local(last_run_at), delta, self.to_local(now)
  474. def remaining_estimate(self, last_run_at, ffwd=ffwd):
  475. """Estimate of next run time.
  476. Returns when the periodic task should run next as a
  477. :class:`~datetime.timedelta`.
  478. """
  479. # pylint: disable=redefined-outer-name
  480. # caching global ffwd
  481. return remaining(*self.remaining_delta(last_run_at, ffwd=ffwd))
  482. def is_due(self, last_run_at):
  483. """Return tuple of ``(is_due, next_time_to_run)``.
  484. Note:
  485. Next time to run is in seconds.
  486. SeeAlso:
  487. :meth:`celery.schedules.schedule.is_due` for more information.
  488. """
  489. rem_delta = self.remaining_estimate(last_run_at)
  490. rem = max(rem_delta.total_seconds(), 0)
  491. due = rem == 0
  492. if due:
  493. rem_delta = self.remaining_estimate(self.now())
  494. rem = max(rem_delta.total_seconds(), 0)
  495. return schedstate(due, rem)
  496. def __eq__(self, other):
  497. if isinstance(other, crontab):
  498. return (
  499. other.month_of_year == self.month_of_year and
  500. other.day_of_month == self.day_of_month and
  501. other.day_of_week == self.day_of_week and
  502. other.hour == self.hour and
  503. other.minute == self.minute
  504. )
  505. return NotImplemented
  506. def __ne__(self, other):
  507. res = self.__eq__(other)
  508. if res is NotImplemented:
  509. return True
  510. return not res
  511. def maybe_schedule(s, relative=False, app=None):
  512. """Return schedule from number, timedelta, or actual schedule."""
  513. if s is not None:
  514. if isinstance(s, numbers.Number):
  515. s = timedelta(seconds=s)
  516. if isinstance(s, timedelta):
  517. return schedule(s, relative, app=app)
  518. else:
  519. s.app = app
  520. return s
  521. @python_2_unicode_compatible
  522. class solar(BaseSchedule):
  523. """Solar event.
  524. A solar event can be used as the ``run_every`` value of a
  525. periodic task entry to schedule based on certain solar events.
  526. Notes:
  527. Available event valus are:
  528. - ``dawn_astronomical``
  529. - ``dawn_nautical``
  530. - ``dawn_civil``
  531. - ``sunrise``
  532. - ``solar_noon``
  533. - ``sunset``
  534. - ``dusk_civil``
  535. - ``dusk_nautical``
  536. - ``dusk_astronomical``
  537. Arguments:
  538. event (str): Solar event that triggers this task.
  539. See note for available values.
  540. lat (int): The latitude of the observer.
  541. lon (int): The longitude of the observer.
  542. nowfun (Callable): Function returning the current date and time
  543. as a class:`~datetime.datetime`.
  544. app (~@Celery): Celery app instance.
  545. """
  546. _all_events = {
  547. 'dawn_astronomical',
  548. 'dawn_nautical',
  549. 'dawn_civil',
  550. 'sunrise',
  551. 'solar_noon',
  552. 'sunset',
  553. 'dusk_civil',
  554. 'dusk_nautical',
  555. 'dusk_astronomical',
  556. }
  557. _horizons = {
  558. 'dawn_astronomical': '-18',
  559. 'dawn_nautical': '-12',
  560. 'dawn_civil': '-6',
  561. 'sunrise': '-0:34',
  562. 'solar_noon': '0',
  563. 'sunset': '-0:34',
  564. 'dusk_civil': '-6',
  565. 'dusk_nautical': '-12',
  566. 'dusk_astronomical': '18',
  567. }
  568. _methods = {
  569. 'dawn_astronomical': 'next_rising',
  570. 'dawn_nautical': 'next_rising',
  571. 'dawn_civil': 'next_rising',
  572. 'sunrise': 'next_rising',
  573. 'solar_noon': 'next_transit',
  574. 'sunset': 'next_setting',
  575. 'dusk_civil': 'next_setting',
  576. 'dusk_nautical': 'next_setting',
  577. 'dusk_astronomical': 'next_setting',
  578. }
  579. _use_center_l = {
  580. 'dawn_astronomical': True,
  581. 'dawn_nautical': True,
  582. 'dawn_civil': True,
  583. 'sunrise': False,
  584. 'solar_noon': True,
  585. 'sunset': False,
  586. 'dusk_civil': True,
  587. 'dusk_nautical': True,
  588. 'dusk_astronomical': True,
  589. }
  590. def __init__(self, event, lat, lon, **kwargs):
  591. self.ephem = __import__('ephem')
  592. self.event = event
  593. self.lat = lat
  594. self.lon = lon
  595. super(solar, self).__init__(**kwargs)
  596. if event not in self._all_events:
  597. raise ValueError(SOLAR_INVALID_EVENT.format(
  598. event=event, all_events=', '.join(sorted(self._all_events)),
  599. ))
  600. if lat < -90 or lat > 90:
  601. raise ValueError(SOLAR_INVALID_LATITUDE.format(lat=lat))
  602. if lon < -180 or lon > 180:
  603. raise ValueError(SOLAR_INVALID_LONGITUDE.format(lon=lon))
  604. cal = self.ephem.Observer()
  605. cal.lat = str(lat)
  606. cal.lon = str(lon)
  607. cal.elev = 0
  608. cal.horizon = self._horizons[event]
  609. cal.pressure = 0
  610. self.cal = cal
  611. self.method = self._methods[event]
  612. self.use_center = self._use_center_l[event]
  613. def __reduce__(self):
  614. return self.__class__, (self.event, self.lat, self.lon)
  615. def __repr__(self):
  616. return '<solar: {0} at latitude {1}, longitude: {2}>'.format(
  617. self.event, self.lat, self.lon,
  618. )
  619. def remaining_estimate(self, last_run_at):
  620. """Return estimate of next time to run.
  621. Returns:
  622. ~datetime.timedelta: when the periodic task should
  623. run next, or if it shouldn't run today (e.g., the sun does
  624. not rise today), returns the time when the next check
  625. should take place.
  626. """
  627. last_run_at = self.maybe_make_aware(last_run_at)
  628. last_run_at_utc = localize(last_run_at, timezone.utc)
  629. self.cal.date = last_run_at_utc
  630. try:
  631. next_utc = getattr(self.cal, self.method)(
  632. self.ephem.Sun(),
  633. start=last_run_at_utc, use_center=self.use_center,
  634. )
  635. except self.ephem.CircumpolarError: # pragma: no cover
  636. # Sun won't rise/set today. Check again tomorrow
  637. # (specifically, after the next anti-transit).
  638. next_utc = (
  639. self.cal.next_antitransit(self.ephem.Sun()) +
  640. timedelta(minutes=1)
  641. )
  642. next = self.maybe_make_aware(next_utc.datetime())
  643. now = self.maybe_make_aware(self.now())
  644. delta = next - now
  645. return delta
  646. def is_due(self, last_run_at):
  647. """Return tuple of ``(is_due, next_time_to_run)``.
  648. Note:
  649. next time to run is in seconds.
  650. See Also:
  651. :meth:`celery.schedules.schedule.is_due` for more information.
  652. """
  653. rem_delta = self.remaining_estimate(last_run_at)
  654. rem = max(rem_delta.total_seconds(), 0)
  655. due = rem == 0
  656. if due:
  657. rem_delta = self.remaining_estimate(self.now())
  658. rem = max(rem_delta.total_seconds(), 0)
  659. return schedstate(due, rem)
  660. def __eq__(self, other):
  661. if isinstance(other, solar):
  662. return (
  663. other.event == self.event and
  664. other.lat == self.lat and
  665. other.lon == self.lon
  666. )
  667. return NotImplemented
  668. def __ne__(self, other):
  669. res = self.__eq__(other)
  670. if res is NotImplemented:
  671. return True
  672. return not res