You've already forked MicroPythonOS
mirror of
https://github.com/m5stack/MicroPythonOS.git
synced 2026-05-20 11:51:27 -07:00
API: add TaskManager that wraps asyncio
This commit is contained in:
@@ -5,6 +5,7 @@ from .net.connectivity_manager import ConnectivityManager
|
||||
from .content.intent import Intent
|
||||
from .activity_navigator import ActivityNavigator
|
||||
from .content.package_manager import PackageManager
|
||||
from .task_manager import TaskManager
|
||||
|
||||
# Common activities (optional)
|
||||
from .app.activities.chooser import ChooserActivity
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import task_handler
|
||||
import _thread
|
||||
import lvgl as lv
|
||||
import mpos
|
||||
import mpos.apps
|
||||
import mpos.config
|
||||
import mpos.ui
|
||||
@@ -71,6 +72,8 @@ except Exception as e:
|
||||
# This will throw an exception if there is already a "/builtin" folder present
|
||||
print("main.py: WARNING: could not import/run freezefs_mount_builtin: ", e)
|
||||
|
||||
mpos.TaskManager()
|
||||
|
||||
try:
|
||||
from mpos.net.wifi_service import WifiService
|
||||
_thread.stack_size(mpos.apps.good_stack_size())
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import asyncio # this is the only place where asyncio is allowed to be imported - apps should not use it directly but use this TaskManager
|
||||
import _thread
|
||||
|
||||
class TaskManager:
|
||||
|
||||
task_list = [] # might be good to periodically remove tasks that are done, to prevent this list from growing huge
|
||||
|
||||
def __init__(self):
|
||||
print("TaskManager starting asyncio_thread")
|
||||
_thread.stack_size(1024) # tiny stack size is enough for this simple thread
|
||||
_thread.start_new_thread(asyncio.run, (self._asyncio_thread(), ))
|
||||
|
||||
async def _asyncio_thread(self):
|
||||
print("asyncio_thread started")
|
||||
while True:
|
||||
#print("asyncio_thread tick")
|
||||
await asyncio.sleep_ms(100) # This delay determines how quickly new tasks can be started, so keep it below human reaction speed
|
||||
print("WARNING: asyncio_thread exited, this shouldn't happen because now asyncio.create_task() won't work anymore!")
|
||||
|
||||
@classmethod
|
||||
def create_task(cls, coroutine):
|
||||
cls.task_list.append(asyncio.create_task(coroutine))
|
||||
|
||||
@classmethod
|
||||
def list_tasks(cls):
|
||||
for index, task in enumerate(cls.task_list):
|
||||
print(f"task {index}: ph_key:{task.ph_key} done:{task.done()} running {task.coro}")
|
||||
|
||||
@staticmethod
|
||||
def sleep_ms(ms):
|
||||
return asyncio.sleep_ms(ms)
|
||||
|
||||
@staticmethod
|
||||
def sleep(s):
|
||||
return asyncio.sleep(s)
|
||||
Reference in New Issue
Block a user