| Total Complexity | 6 |
| Total Lines | 35 |
| Duplicated Lines | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
| 1 | import asyncio |
||
| 10 | class LoaferRunner: |
||
| 11 | |||
| 12 | def __init__(self, loop=None, max_workers=None, on_stop_callback=None): |
||
| 13 | self._on_stop_callback = on_stop_callback |
||
| 14 | self._loop = loop or asyncio.get_event_loop() |
||
| 15 | |||
| 16 | # XXX: See https://github.com/python/asyncio/issues/258 |
||
| 17 | # The minimum value depends on the number of cores in the machine |
||
| 18 | # See https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor |
||
| 19 | self._executor = ThreadPoolExecutor(max_workers) |
||
| 20 | self._loop.set_default_executor(self._executor) |
||
| 21 | |||
| 22 | def start(self, future=None, run_forever=True): |
||
| 23 | start = 'Starting Loafer - (pid={} / run_forever={}) ...' |
||
| 24 | logger.info(start.format(os.getpid(), run_forever)) |
||
| 25 | |||
| 26 | self._loop.add_signal_handler(signal.SIGINT, self.stop) |
||
| 27 | self._loop.add_signal_handler(signal.SIGTERM, self.stop) |
||
| 28 | |||
| 29 | try: |
||
| 30 | if run_forever: |
||
| 31 | self._loop.run_forever() |
||
| 32 | else: |
||
| 33 | self._loop.run_until_complete(future) |
||
| 34 | finally: |
||
| 35 | self._loop.close() |
||
| 36 | |||
| 37 | def stop(self, *args, **kwargs): |
||
| 38 | logger.info('Stopping Loafer ...') |
||
| 39 | if callable(self._on_stop_callback): |
||
| 40 | self._on_stop_callback() |
||
| 41 | |||
| 42 | self._executor.shutdown(wait=True) |
||
| 43 | if self._loop.is_running(): |
||
| 44 | self._loop.stop() |
||
| 45 |