schedules.py 29 KB

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