pool.py 2.6 KB

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