beat.py 12 KB

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