matrix-clock/src/handler/action_queue.py

45 lines
1.8 KiB
Python
Raw Normal View History

import asyncio
2024-01-30 20:08:32 +01:00
import logging
class ActionQueue:
2023-12-23 18:57:55 +01:00
def __init__(self) -> None:
2024-01-30 19:58:21 +01:00
self.queued_actions: asyncio.Queue = asyncio.Queue()
2024-01-30 20:04:01 +01:00
self.idle_action: tuple = (None,[],{})
2024-01-30 19:58:21 +01:00
self.queue_task = asyncio.create_task(self.run_queue())
self.idle_action_task = None
2024-01-30 20:08:32 +01:00
def __del___(self):
self.queue_task.cancel()
if self.idle_action_task is not None:
self.idle_action_task.cancel()
async def run_queue(self):
2024-01-30 20:01:20 +01:00
while True:
2024-01-30 20:08:32 +01:00
try:
2024-01-30 20:13:11 +01:00
if self.queued_actions.empty() and self.idle_action is not None and self.idle_action[0] is not None:
2024-01-30 20:08:32 +01:00
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()
2024-01-30 19:58:21 +01:00
2024-01-30 20:08:32 +01:00
if self.idle_action_task is not None:
self.idle_action_task.cancel()
self.idle_action_task = None
2024-01-30 20:13:11 +01:00
if action is not None and action[0] is not None: # If none -> Is idle update
2024-01-30 20:08:32 +01:00
try:
await action[0](*(action[1]), **(action[2]))
except Exception as ex:
logging.exception("Something went wrong during execution of action.", ex)
2024-01-30 19:58:21 +01:00
2024-01-30 20:08:32 +01:00
except Exception as ex:
logging.exception("Something went wrong in queue task.", ex)
async def add_action_to_queue(self, action, *args, **kwargs):
2024-01-30 19:58:21 +01:00
await self.queued_actions.put((action, args, kwargs))
2024-01-30 19:58:21 +01:00
async def set_idle_action(self, action, *args, **kwargs):
self.idle_action = (action, args, kwargs)
await self.queued_actions.put(None)