beat.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. """
  2. Periodic Task Scheduler
  3. """
  4. import time
  5. import shelve
  6. import sys
  7. import threading
  8. import traceback
  9. import multiprocessing
  10. from datetime import datetime
  11. from celery import platforms
  12. from celery import registry
  13. from celery.app import app_or_default
  14. from celery.log import SilenceRepeated
  15. from celery.schedules import maybe_schedule
  16. from celery.utils import cached_property, instantiate
  17. from celery.utils.compat import UserDict
  18. from celery.utils.timeutils import humanize_seconds
  19. class SchedulingError(Exception):
  20. """An error occured while scheduling a task."""
  21. class ScheduleEntry(object):
  22. """An entry in the scheduler.
  23. :param name: see :attr:`name`.
  24. :param schedule: see :attr:`schedule`.
  25. :param args: see :attr:`args`.
  26. :param kwargs: see :attr:`kwargs`.
  27. :keyword last_run_at: see :attr:`last_run_at`.
  28. :keyword total_run_count: see :attr:`total_run_count`.
  29. .. attribute:: name
  30. The task name.
  31. .. attribute:: schedule
  32. The schedule (run_every/crontab)
  33. .. attribute:: args
  34. Args to apply.
  35. .. attribute:: kwargs
  36. Keyword arguments to apply.
  37. .. attribute:: last_run_at
  38. The time and date of when this task was last run.
  39. .. attribute:: total_run_count
  40. Total number of times this periodic task has been executed.
  41. """
  42. def __init__(self, name=None, task=None, last_run_at=None,
  43. total_run_count=None, schedule=None, args=(), kwargs={},
  44. options={}, relative=False):
  45. self.name = name
  46. self.task = task
  47. self.schedule = maybe_schedule(schedule, relative)
  48. self.args = args
  49. self.kwargs = kwargs
  50. self.options = options
  51. self.last_run_at = last_run_at or datetime.now()
  52. self.total_run_count = total_run_count or 0
  53. def next(self, last_run_at=None):
  54. """Returns a new instance of the same class, but with
  55. its date and count fields updated."""
  56. last_run_at = last_run_at or datetime.now()
  57. total_run_count = self.total_run_count + 1
  58. return self.__class__(**dict(self,
  59. last_run_at=last_run_at,
  60. total_run_count=total_run_count))
  61. def update(self, other):
  62. """Update values from another entry.
  63. Does only update "editable" fields (schedule, args,
  64. kwargs, options).
  65. """
  66. self.task = other.task
  67. self.schedule = other.schedule
  68. self.args = other.args
  69. self.kwargs = other.kwargs
  70. self.options = other.options
  71. def is_due(self):
  72. """See :meth:`celery.task.base.PeriodicTask.is_due`."""
  73. return self.schedule.is_due(self.last_run_at)
  74. def __iter__(self):
  75. return vars(self).iteritems()
  76. def __repr__(self):
  77. return "<Entry: %s %s(*%s, **%s) {%s}>" % (self.name,
  78. self.task,
  79. self.args,
  80. self.kwargs,
  81. self.schedule)
  82. class Scheduler(UserDict):
  83. """Scheduler for periodic tasks.
  84. :keyword schedule: see :attr:`schedule`.
  85. :keyword logger: see :attr:`logger`.
  86. :keyword max_interval: see :attr:`max_interval`.
  87. .. attribute:: schedule
  88. The schedule dict/shelve.
  89. .. attribute:: logger
  90. The logger to use.
  91. .. attribute:: max_interval
  92. Maximum time to sleep between re-checking the schedule.
  93. """
  94. Entry = ScheduleEntry
  95. def __init__(self, schedule=None, logger=None, max_interval=None,
  96. app=None, Publisher=None, lazy=False, **kwargs):
  97. UserDict.__init__(self)
  98. if schedule is None:
  99. schedule = {}
  100. self.app = app_or_default(app)
  101. conf = self.app.conf
  102. self.data = schedule
  103. self.logger = logger or self.app.log.get_default_logger(
  104. name="celery.beat")
  105. self.max_interval = max_interval or conf.CELERYBEAT_MAX_LOOP_INTERVAL
  106. self.Publisher = Publisher or self.app.amqp.TaskPublisher
  107. if not lazy:
  108. self.setup_schedule()
  109. def maybe_due(self, entry, publisher=None):
  110. is_due, next_time_to_run = entry.is_due()
  111. if is_due:
  112. self.logger.debug("Scheduler: Sending due task %s" % entry.task)
  113. try:
  114. result = self.apply_async(entry, publisher=publisher)
  115. except Exception, exc:
  116. self.logger.error("Message Error: %s\n%s" % (exc,
  117. traceback.format_stack()), exc_info=sys.exc_info())
  118. else:
  119. self.logger.debug("%s sent. id->%s" % (entry.task,
  120. result.task_id))
  121. return next_time_to_run
  122. def tick(self):
  123. """Run a tick, that is one iteration of the scheduler.
  124. Executes all due tasks.
  125. """
  126. remaining_times = []
  127. try:
  128. for entry in self.schedule.itervalues():
  129. next_time_to_run = self.maybe_due(entry, self.publisher)
  130. if next_time_to_run:
  131. remaining_times.append(next_time_to_run)
  132. except RuntimeError:
  133. pass
  134. return min(remaining_times + [self.max_interval])
  135. def reserve(self, entry):
  136. new_entry = self.schedule[entry.name] = entry.next()
  137. return new_entry
  138. def apply_async(self, entry, publisher=None, **kwargs):
  139. # Update timestamps and run counts before we actually execute,
  140. # so we have that done if an exception is raised (doesn't schedule
  141. # forever.)
  142. entry = self.reserve(entry)
  143. try:
  144. task = registry.tasks[entry.task]
  145. except KeyError:
  146. task = None
  147. try:
  148. if task:
  149. result = task.apply_async(entry.args, entry.kwargs,
  150. publisher=publisher,
  151. **entry.options)
  152. else:
  153. result = self.send_task(entry.task, entry.args, entry.kwargs,
  154. publisher=publisher,
  155. **entry.options)
  156. except Exception, exc:
  157. raise SchedulingError("Couldn't apply scheduled task %s: %s" % (
  158. entry.name, exc))
  159. return result
  160. def send_task(self, *args, **kwargs): # pragma: no cover
  161. return self.app.send_task(*args, **kwargs)
  162. def setup_schedule(self):
  163. pass
  164. def sync(self):
  165. pass
  166. def close(self):
  167. self.sync()
  168. def add(self, **kwargs):
  169. entry = self.Entry(**kwargs)
  170. self.schedule[entry.name] = entry
  171. return entry
  172. def update_from_dict(self, dict_):
  173. self.update(dict((name, self.Entry(name, **entry))
  174. for name, entry in dict_.items()))
  175. def merge_inplace(self, b):
  176. A, B = set(self.keys()), set(b.keys())
  177. # Remove items from disk not in the schedule anymore.
  178. for key in A ^ B:
  179. self.pop(key, None)
  180. # Update and add new items in the schedule
  181. for key in B:
  182. entry = self.Entry(**dict(b[key]))
  183. if self.get(key):
  184. self[key].update(entry)
  185. else:
  186. self[key] = entry
  187. def get_schedule(self):
  188. return self.data
  189. @cached_property
  190. def connection(self):
  191. return self.app.broker_connection()
  192. @cached_property
  193. def publisher(self):
  194. return self.Publisher(connection=self.connection)
  195. @property
  196. def schedule(self):
  197. return self.get_schedule()
  198. @property
  199. def info(self):
  200. return ""
  201. class PersistentScheduler(Scheduler):
  202. persistence = shelve
  203. _store = None
  204. def __init__(self, *args, **kwargs):
  205. self.schedule_filename = kwargs.get("schedule_filename")
  206. Scheduler.__init__(self, *args, **kwargs)
  207. def setup_schedule(self):
  208. self._store = self.persistence.open(self.schedule_filename)
  209. self.data = self._store
  210. self.merge_inplace(self.app.conf.CELERYBEAT_SCHEDULE)
  211. self.sync()
  212. self.data = self._store
  213. def sync(self):
  214. if self._store is not None:
  215. self.logger.debug("CeleryBeat: Syncing schedule to disk...")
  216. self._store.sync()
  217. def close(self):
  218. self.sync()
  219. self._store.close()
  220. @property
  221. def info(self):
  222. return " . db -> %s" % (self.schedule_filename, )
  223. class Service(object):
  224. scheduler_cls = PersistentScheduler
  225. def __init__(self, logger=None,
  226. max_interval=None, schedule=None, schedule_filename=None,
  227. scheduler_cls=None, app=None):
  228. self.app = app_or_default(app)
  229. self.max_interval = max_interval or \
  230. self.app.conf.CELERYBEAT_MAX_LOOP_INTERVAL
  231. self.scheduler_cls = scheduler_cls or self.scheduler_cls
  232. self.logger = logger or self.app.log.get_default_logger(
  233. name="celery.beat")
  234. self.schedule = schedule or self.app.conf.CELERYBEAT_SCHEDULE
  235. self.schedule_filename = schedule_filename or \
  236. self.app.conf.CELERYBEAT_SCHEDULE_FILENAME
  237. self._shutdown = threading.Event()
  238. self._stopped = threading.Event()
  239. silence = self.max_interval < 60 and 10 or 1
  240. self.debug = SilenceRepeated(self.logger.debug,
  241. max_iterations=silence)
  242. def start(self, embedded_process=False):
  243. self.logger.info("Celerybeat: Starting...")
  244. self.logger.debug("Celerybeat: "
  245. "Ticking with max interval->%s" % (
  246. humanize_seconds(self.scheduler.max_interval)))
  247. if embedded_process:
  248. platforms.set_process_title("celerybeat")
  249. try:
  250. try:
  251. while not self._shutdown.isSet():
  252. interval = self.scheduler.tick()
  253. self.debug("Celerybeat: Waking up %s." % (
  254. humanize_seconds(interval, prefix="in ")))
  255. time.sleep(interval)
  256. except (KeyboardInterrupt, SystemExit):
  257. self._shutdown.set()
  258. finally:
  259. self.sync()
  260. def sync(self):
  261. self.scheduler.close()
  262. self._stopped.set()
  263. def stop(self, wait=False):
  264. self.logger.info("Celerybeat: Shutting down...")
  265. self._shutdown.set()
  266. wait and self._stopped.wait() # block until shutdown done.
  267. def get_scheduler(self, lazy=False):
  268. filename = self.schedule_filename
  269. scheduler = instantiate(self.scheduler_cls,
  270. app=self.app,
  271. schedule_filename=filename,
  272. logger=self.logger,
  273. max_interval=self.max_interval,
  274. lazy=lazy)
  275. if not lazy:
  276. scheduler.update_from_dict(self.schedule)
  277. return scheduler
  278. @cached_property
  279. def scheduler(self):
  280. return self.get_scheduler()
  281. class _Threaded(threading.Thread):
  282. """Embedded task scheduler using threading."""
  283. def __init__(self, *args, **kwargs):
  284. super(_Threaded, self).__init__()
  285. self.service = Service(*args, **kwargs)
  286. self.setDaemon(True)
  287. self.setName("Beat")
  288. def run(self):
  289. self.service.start()
  290. def stop(self):
  291. self.service.stop(wait=True)
  292. class _Process(multiprocessing.Process):
  293. """Embedded task scheduler using multiprocessing."""
  294. def __init__(self, *args, **kwargs):
  295. super(_Process, self).__init__()
  296. self.service = Service(*args, **kwargs)
  297. self.name = "Beat"
  298. def run(self):
  299. platforms.reset_signal("SIGTERM")
  300. self.service.start(embedded_process=True)
  301. def stop(self):
  302. self.service.stop()
  303. self.terminate()
  304. def EmbeddedService(*args, **kwargs):
  305. """Return embedded clock service.
  306. :keyword thread: Run threaded instead of as a separate process.
  307. Default is :const:`False`.
  308. """
  309. if kwargs.pop("thread", False):
  310. # Need short max interval to be able to stop thread
  311. # in reasonable time.
  312. kwargs.setdefault("max_interval", 1)
  313. return _Threaded(*args, **kwargs)
  314. return _Process(*args, **kwargs)