beat.py 12 KB

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