schedules.py 26 KB

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