beat.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. """
  2. Periodic Task Scheduler
  3. """
  4. import time
  5. import shelve
  6. import threading
  7. import multiprocessing
  8. from datetime import datetime
  9. from UserDict import UserDict
  10. from celery import log
  11. from celery import conf
  12. from celery import platform
  13. from celery.execute import send_task
  14. from celery.schedules import maybe_schedule
  15. from celery.messaging import establish_connection
  16. from celery.utils import instantiate
  17. from celery.utils.info 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. **kwargs):
  96. UserDict.__init__(self)
  97. if schedule is None:
  98. schedule = {}
  99. self.data = schedule
  100. self.logger = logger or log.get_default_logger(name="celery.beat")
  101. self.max_interval = max_interval or conf.CELERYBEAT_MAX_LOOP_INTERVAL
  102. self.setup_schedule()
  103. def maybe_due(self, entry, connection=None):
  104. is_due, next_time_to_run = entry.is_due()
  105. if is_due:
  106. self.logger.debug("Scheduler: Sending due task %s" % entry.task)
  107. try:
  108. result = self.apply_async(entry, connection=connection)
  109. except SchedulingError, exc:
  110. self.logger.error("Scheduler: %s" % exc)
  111. else:
  112. self.logger.debug("%s sent. id->%s" % (entry.task,
  113. result.task_id))
  114. return next_time_to_run
  115. def tick(self):
  116. """Run a tick, that is one iteration of the scheduler.
  117. Executes all due tasks.
  118. """
  119. remaining_times = []
  120. connection = establish_connection()
  121. try:
  122. try:
  123. for entry in self.schedule.itervalues():
  124. next_time_to_run = self.maybe_due(entry, connection)
  125. if next_time_to_run:
  126. remaining_times.append(next_time_to_run)
  127. except RuntimeError:
  128. pass
  129. finally:
  130. connection.close()
  131. return min(remaining_times + [self.max_interval])
  132. def reserve(self, entry):
  133. new_entry = self[entry.name] = entry.next()
  134. return new_entry
  135. def apply_async(self, entry, connection=None, **kwargs):
  136. # Update timestamps and run counts before we actually execute,
  137. # so we have that done if an exception is raised (doesn't schedule
  138. # forever.)
  139. entry = self.reserve(entry)
  140. try:
  141. result = self.send_task(entry.task, entry.args, entry.kwargs,
  142. connection=connection, **entry.options)
  143. except Exception, exc:
  144. raise SchedulingError("Couldn't apply scheduled task %s: %s" % (
  145. entry.name, exc))
  146. return result
  147. def send_task(self, *args, **kwargs): # pragma: no cover
  148. return send_task(*args, **kwargs)
  149. def setup_schedule(self):
  150. pass
  151. def sync(self):
  152. pass
  153. def close(self):
  154. self.sync()
  155. def add(self, **kwargs):
  156. entry = self.Entry(**kwargs)
  157. self[entry.name] = entry
  158. return entry
  159. def update_from_dict(self, dict_):
  160. self.update(dict((name, self.Entry(name, **entry))
  161. for name, entry in dict_.items()))
  162. def merge_inplace(self, b):
  163. A, B = set(self.keys()), set(b.keys())
  164. # Remove items from disk not in the schedule anymore.
  165. for key in A ^ B:
  166. self.pop(key, None)
  167. # Update and add new items in the schedule
  168. for key in B:
  169. entry = self.Entry(**dict(b[key]))
  170. if self.get(key):
  171. self[key].update(entry)
  172. else:
  173. self[key] = entry
  174. def get_schedule(self):
  175. return self.data
  176. @property
  177. def schedule(self):
  178. return self.get_schedule()
  179. class PersistentScheduler(Scheduler):
  180. persistence = shelve
  181. _store = None
  182. def __init__(self, *args, **kwargs):
  183. self.schedule_filename = kwargs.get("schedule_filename")
  184. Scheduler.__init__(self, *args, **kwargs)
  185. def setup_schedule(self):
  186. self._store = self.persistence.open(self.schedule_filename)
  187. self.data = self._store
  188. self.merge_inplace(conf.CELERYBEAT_SCHEDULE)
  189. self.sync()
  190. self.data = self._store
  191. def sync(self):
  192. if self._store is not None:
  193. self.logger.debug("CeleryBeat: Syncing schedule to disk...")
  194. self._store.sync()
  195. def close(self):
  196. self.sync()
  197. self._store.close()
  198. class Service(object):
  199. scheduler_cls = PersistentScheduler
  200. def __init__(self, logger=None,
  201. max_interval=conf.CELERYBEAT_MAX_LOOP_INTERVAL,
  202. schedule=conf.CELERYBEAT_SCHEDULE,
  203. schedule_filename=conf.CELERYBEAT_SCHEDULE_FILENAME,
  204. scheduler_cls=None):
  205. self.max_interval = max_interval
  206. self.scheduler_cls = scheduler_cls or self.scheduler_cls
  207. self.logger = logger or log.get_default_logger(name="celery.beat")
  208. self.schedule = schedule
  209. self.schedule_filename = schedule_filename
  210. self._scheduler = None
  211. self._shutdown = threading.Event()
  212. self._stopped = threading.Event()
  213. silence = self.max_interval < 60 and 10 or 1
  214. self.debug = log.SilenceRepeated(self.logger.debug,
  215. max_iterations=silence)
  216. def start(self, embedded_process=False):
  217. self.logger.info("Celerybeat: Starting...")
  218. self.logger.debug("Celerybeat: "
  219. "Ticking with max interval->%s" % (
  220. humanize_seconds(self.scheduler.max_interval)))
  221. if embedded_process:
  222. platform.set_process_title("celerybeat")
  223. try:
  224. try:
  225. while not self._shutdown.isSet():
  226. interval = self.scheduler.tick()
  227. self.debug("Celerybeat: Waking up %s." % (
  228. humanize_seconds(interval, prefix="in ")))
  229. time.sleep(interval)
  230. except (KeyboardInterrupt, SystemExit):
  231. self._shutdown.set()
  232. finally:
  233. self.sync()
  234. def sync(self):
  235. self.scheduler.close()
  236. self._stopped.set()
  237. def stop(self, wait=False):
  238. self.logger.info("Celerybeat: Shutting down...")
  239. self._shutdown.set()
  240. wait and self._stopped.wait() # block until shutdown done.
  241. @property
  242. def scheduler(self):
  243. if self._scheduler is None:
  244. filename = self.schedule_filename
  245. self._scheduler = instantiate(self.scheduler_cls,
  246. schedule_filename=filename,
  247. logger=self.logger,
  248. max_interval=self.max_interval)
  249. self._scheduler.update_from_dict(self.schedule)
  250. return self._scheduler
  251. class _Threaded(threading.Thread):
  252. """Embedded task scheduler using threading."""
  253. def __init__(self, *args, **kwargs):
  254. super(_Threaded, self).__init__()
  255. self.service = Service(*args, **kwargs)
  256. self.setDaemon(True)
  257. self.setName("Beat")
  258. def run(self):
  259. self.service.start()
  260. def stop(self):
  261. self.service.stop(wait=True)
  262. class _Process(multiprocessing.Process):
  263. """Embedded task scheduler using multiprocessing."""
  264. def __init__(self, *args, **kwargs):
  265. super(_Process, self).__init__()
  266. self.service = Service(*args, **kwargs)
  267. self.name = "Beat"
  268. def run(self):
  269. platform.reset_signal("SIGTERM")
  270. self.service.start(embedded_process=True)
  271. def stop(self):
  272. self.service.stop()
  273. self.terminate()
  274. def EmbeddedService(*args, **kwargs):
  275. """Return embedded clock service.
  276. :keyword thread: Run threaded instead of as a separate process.
  277. Default is ``False``.
  278. """
  279. if kwargs.pop("thread", False):
  280. # Need short max interval to be able to stop thread
  281. # in reasonable time.
  282. kwargs.setdefault("max_interval", 1)
  283. return _Threaded(*args, **kwargs)
  284. return _Process(*args, **kwargs)