schedules.py 28 KB

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