schedules.py 27 KB

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