Allowing non-awaitable actions

This commit is contained in:
Maximilian Giller 2024-01-30 20:25:48 +01:00
parent 0ab2d6996e
commit da780894d0

View file

@ -4,7 +4,7 @@ import logging
class ActionQueue: class ActionQueue:
def __init__(self) -> None: def __init__(self) -> None:
self.queued_actions: asyncio.Queue = asyncio.Queue() self.queued_actions: asyncio.Queue = asyncio.Queue()
self.idle_action: tuple = (None,[],{}) self.idle_action: tuple = None
self.queue_task = asyncio.create_task(self.run_queue()) self.queue_task = asyncio.create_task(self.run_queue())
self.idle_action_task = None self.idle_action_task = None
@ -17,7 +17,7 @@ class ActionQueue:
async def run_queue(self): async def run_queue(self):
while True: while True:
try: try:
if self.queued_actions.empty() and self.idle_action is not None and self.idle_action[0] is not None: if self.queued_actions.empty() and self.idle_action is not None:
self.idle_action_task = asyncio.create_task(self.idle_action[0](*(self.idle_action[1]), **(self.idle_action[2]))) self.idle_action_task = asyncio.create_task(self.idle_action[0](*(self.idle_action[1]), **(self.idle_action[2])))
action = await self.queued_actions.get() action = await self.queued_actions.get()
@ -26,9 +26,11 @@ class ActionQueue:
self.idle_action_task.cancel() self.idle_action_task.cancel()
self.idle_action_task = None self.idle_action_task = None
if action is not None and action[0] is not None: # If none -> Is idle update if action is not None: # If none -> Is idle update
try: try:
await action[0](*(action[1]), **(action[2])) awaitable = action[0](*(action[1]), **(action[2]))
if awaitable is not None:
await awaitable
except Exception as ex: except Exception as ex:
logging.exception("Something went wrong during execution of action.", ex) logging.exception("Something went wrong during execution of action.", ex)
@ -39,6 +41,10 @@ class ActionQueue:
await self.queued_actions.put((action, args, kwargs)) await self.queued_actions.put((action, args, kwargs))
async def set_idle_action(self, action, *args, **kwargs): async def set_idle_action(self, action, *args, **kwargs):
if action is None:
self.idle_action = None
else:
self.idle_action = (action, args, kwargs) self.idle_action = (action, args, kwargs)
await self.queued_actions.put(None) await self.queued_actions.put(None)