schedules.py 27 KB

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