Completed
Push — master ( dc3db7...c94c8e )
by George
02:13
created

LoaferRunner   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 35
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A start() 0 14 2
A stop() 0 8 3
A __init__() 0 9 1
1
import asyncio
2
from concurrent.futures import ThreadPoolExecutor
3
import logging
4
import os
5
import signal
6
7
logger = logging.getLogger(__name__)
8
9
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):
0 ignored issues
show
Unused Code introduced by
The argument args seems to be unused.
Loading history...
Unused Code introduced by
The argument kwargs seems to be unused.
Loading history...
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