-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmain.py
65 lines (54 loc) · 2.22 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from logs import global_logger
import threading
import time
import code
from importlib import reload
from abc import ABC, abstractmethod
"""
Main script for AutoAquaponics system.
This script contains a Task class that defines a task that can run concurrently,
as well as a TaskHandle class that can be used to run tasks in separate threads.
The script starts a REPL that can be used to manage these tasks.
To create a task, use the REPL to import the desired module, e.g. `import
notifs`, which contains a definition of the Task class. Then, run task using the
TaskHandle constructor, passing in a valid Task object: `task_notifs =
TaskHandle(notifs.Notifs())`. In addition to storing the resulting task object
in a variable, the task will be added to the `TaskHandle.instances` list. To
stop a task, call the `stop` method on the handle, e.g. `task_notifs.stop()`. To
hot-swap a running module, use `reload(<module>)`, and start the task again. It
is recommended to stop an existing task using a module before reloading the
module.
"""
class Task(ABC):
@abstractmethod
def start(self):
"""Start the task. Called INSIDE this task's dedicated thread."""
pass
@abstractmethod
def stop(self):
"""Stop the task. Called OUTSIDE this task's dedicated thread."""
pass
class TaskHandle:
instances = []
def __init__(self, task: Task):
self.start_time = time.time()
self.task = task
self.thread = threading.Thread(target=task.start)
self.thread.start()
TaskHandle.instances.append(self)
global_logger.info(f"started task: {self}")
def stop(self):
self.task.stop()
self.thread.join()
TaskHandle.instances.remove(self)
global_logger.info(f"stopped task: {self}")
def __repr__(self):
return f"TaskHandle(thread={self.thread.name}, start_time={self.start_time}, task={self.task})"
if __name__ == "__main__":
try:
global_logger.info("starting main script")
code.InteractiveConsole(locals={"TaskHandle": TaskHandle, "reload": reload}).interact()
except Exception as e:
global_logger.error(f"error in main: {str(e)}", exc_info=True)
finally:
global_logger.info("shutting down")