asyncio.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. from __future__ import absolute_import
  2. import sys
  3. from apscheduler.executors.base import BaseExecutor, run_job
  4. from apscheduler.executors.base_py3 import run_coroutine_job
  5. from apscheduler.util import iscoroutinefunction_partial
  6. class AsyncIOExecutor(BaseExecutor):
  7. """
  8. Runs jobs in the default executor of the event loop.
  9. If the job function is a native coroutine function, it is scheduled to be run directly in the
  10. event loop as soon as possible. All other functions are run in the event loop's default
  11. executor which is usually a thread pool.
  12. Plugin alias: ``asyncio``
  13. """
  14. def start(self, scheduler, alias):
  15. super(AsyncIOExecutor, self).start(scheduler, alias)
  16. self._eventloop = scheduler._eventloop
  17. self._pending_futures = set()
  18. def shutdown(self, wait=True):
  19. # There is no way to honor wait=True without converting this method into a coroutine method
  20. for f in self._pending_futures:
  21. if not f.done():
  22. f.cancel()
  23. self._pending_futures.clear()
  24. def _do_submit_job(self, job, run_times):
  25. def callback(f):
  26. self._pending_futures.discard(f)
  27. try:
  28. events = f.result()
  29. except BaseException:
  30. self._run_job_error(job.id, *sys.exc_info()[1:])
  31. else:
  32. self._run_job_success(job.id, events)
  33. if iscoroutinefunction_partial(job.func):
  34. coro = run_coroutine_job(job, job._jobstore_alias, run_times, self._logger.name)
  35. f = self._eventloop.create_task(coro)
  36. else:
  37. f = self._eventloop.run_in_executor(None, run_job, job, job._jobstore_alias, run_times,
  38. self._logger.name)
  39. f.add_done_callback(callback)
  40. self._pending_futures.add(f)