Last active
April 20, 2020 23:36
-
-
Save mauicv/7e35f998ae6cc24f2a0db283219bba2c to your computer and use it in GitHub Desktop.
[thread-controller] #contoller #threads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
from threading import Thread, Timer | |
import logging | |
import sys | |
logging.basicConfig( | |
level=logging.INFO, | |
format='%(threadName)10s %(name)18s: %(message)s', | |
stream=sys.stderr, | |
) | |
class Controller: | |
def __init__(self, processes): | |
self.processes = processes | |
self.threads = [] | |
def run_for(self, seconds): | |
for process in self.processes: | |
self.start_process(process) | |
timer = Timer(seconds, self.stop) | |
timer.start() | |
def stop(self): | |
sys.exit() | |
def start_loop(self, loop): | |
asyncio.set_event_loop(loop) | |
loop.run_forever() | |
def start_process(self, process): | |
loop = asyncio.new_event_loop() | |
t = Thread(target=self.start_loop, args=(loop,)) | |
t.daemon = True | |
t.start() | |
self.threads.append(t) | |
loop.call_soon_threadsafe(process) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment