|
| 1 | +import multiprocessing |
| 2 | +from typing import Any, Callable, Dict |
| 3 | + |
| 4 | +class ProcessManager(object): |
| 5 | + def __init__(self, func: Callable, kill_previous: Any = False, concurrent_running: Any = False) -> None: |
| 6 | + """ProcessManager initializer |
| 7 | +
|
| 8 | + Args: |
| 9 | + func (Callable): function to be executed |
| 10 | + kill_previous (Any, optional): Do you want to kill previous process? if not, new process won't be executed if concurrent is set to False. |
| 11 | + If True, it will kill the unfinished previous process and start the new one. |
| 12 | + Defaults to False. |
| 13 | + concurrent_running (Any, optional): If True, all the process of the function will run concurrently. Defaults to False. |
| 14 | +
|
| 15 | + Raises: |
| 16 | + ValueError: kill_previous and concurrent_running can't be used together. If you kill previous, what do you wanna run concurrently? |
| 17 | + """ |
| 18 | + if concurrent_running and kill_previous: |
| 19 | + raise ValueError("Using kill_previous is not allowed while using concurrent_running.") |
| 20 | + self.func = func |
| 21 | + self.kill_previous = kill_previous |
| 22 | + self.concurrent_running = concurrent_running |
| 23 | + |
| 24 | + """ |
| 25 | + We really don't need to keep track of multiple process. We will need that only when concurrent_running is true |
| 26 | + and we don't need to terminate any process. So, no use of the process ids. |
| 27 | + In the future, all the process management will be added if needed. |
| 28 | + """ |
| 29 | + self.process = None |
| 30 | + |
| 31 | + def run(self, kwargs: Dict = None) -> None: |
| 32 | + """ create a new process of the function |
| 33 | +
|
| 34 | + Args: |
| 35 | + kwargs (Dict, optional): arguments to be passed to your function. Defaults to None. |
| 36 | + """ |
| 37 | + if self.concurrent_running == False and self.process is not None and self.process.is_alive(): |
| 38 | + if self.kill_previous: |
| 39 | + self.kill() |
| 40 | + else: |
| 41 | + return |
| 42 | + |
| 43 | + if kwargs == None: |
| 44 | + self.process = multiprocessing.Process(target=self.func) |
| 45 | + else: |
| 46 | + self.process = multiprocessing.Process(target=self.func, kwargs=kwargs) |
| 47 | + self.process.daemon = True |
| 48 | + self.process.start() |
| 49 | + |
| 50 | + def kill(self) -> None: |
| 51 | + """terminate the currently running process |
| 52 | + """ |
| 53 | + if self.process is not None and self.process.is_alive: |
| 54 | + self.process.terminate() |
0 commit comments