pool.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. from abc import abstractmethod
  2. import concurrent.futures
  3. from apscheduler.executors.base import BaseExecutor, run_job
  4. try:
  5. from concurrent.futures.process import BrokenProcessPool
  6. except ImportError:
  7. BrokenProcessPool = None
  8. class BasePoolExecutor(BaseExecutor):
  9. @abstractmethod
  10. def __init__(self, pool):
  11. super(BasePoolExecutor, self).__init__()
  12. self._pool = pool
  13. def _do_submit_job(self, job, run_times):
  14. def callback(f):
  15. exc, tb = (f.exception_info() if hasattr(f, 'exception_info') else
  16. (f.exception(), getattr(f.exception(), '__traceback__', None)))
  17. if exc:
  18. self._run_job_error(job.id, exc, tb)
  19. else:
  20. self._run_job_success(job.id, f.result())
  21. try:
  22. f = self._pool.submit(run_job, job, job._jobstore_alias, run_times, self._logger.name)
  23. except BrokenProcessPool:
  24. self._logger.warning('Process pool is broken; replacing pool with a fresh instance')
  25. self._pool = self._pool.__class__(self._pool._max_workers)
  26. f = self._pool.submit(run_job, job, job._jobstore_alias, run_times, self._logger.name)
  27. f.add_done_callback(callback)
  28. def shutdown(self, wait=True):
  29. self._pool.shutdown(wait)
  30. class ThreadPoolExecutor(BasePoolExecutor):
  31. """
  32. An executor that runs jobs in a concurrent.futures thread pool.
  33. Plugin alias: ``threadpool``
  34. :param max_workers: the maximum number of spawned threads.
  35. :param pool_kwargs: dict of keyword arguments to pass to the underlying
  36. ThreadPoolExecutor constructor
  37. """
  38. def __init__(self, max_workers=10, pool_kwargs=None):
  39. pool_kwargs = pool_kwargs or {}
  40. pool = concurrent.futures.ThreadPoolExecutor(int(max_workers), **pool_kwargs)
  41. super(ThreadPoolExecutor, self).__init__(pool)
  42. class ProcessPoolExecutor(BasePoolExecutor):
  43. """
  44. An executor that runs jobs in a concurrent.futures process pool.
  45. Plugin alias: ``processpool``
  46. :param max_workers: the maximum number of spawned processes.
  47. :param pool_kwargs: dict of keyword arguments to pass to the underlying
  48. ProcessPoolExecutor constructor
  49. """
  50. def __init__(self, max_workers=10, pool_kwargs=None):
  51. pool_kwargs = pool_kwargs or {}
  52. pool = concurrent.futures.ProcessPoolExecutor(int(max_workers), **pool_kwargs)
  53. super(ProcessPoolExecutor, self).__init__(pool)