From 1854c3ee27818eb73e23489495dd7400deb3a60a Mon Sep 17 00:00:00 2001 From: Maximilian Giller Date: Tue, 30 Jan 2024 19:58:21 +0100 Subject: [PATCH] Dino0040 fixes everthing --- src/handler/action_queue.py | 66 ++++++++++++++----------------------- 1 file changed, 24 insertions(+), 42 deletions(-) diff --git a/src/handler/action_queue.py b/src/handler/action_queue.py index 6de4396..bd3bf05 100644 --- a/src/handler/action_queue.py +++ b/src/handler/action_queue.py @@ -1,54 +1,36 @@ import asyncio from typing import Optional -from enum import Enum - - -class QueueState(Enum): - STOPPED = 0 - IDLE = 1 - POPPING = 2 # As in: Popping actions from the queue and performing them class ActionQueue: def __init__(self) -> None: - self.queued_actions: list = [] + self.queued_actions: asyncio.Queue = asyncio.Queue() self.idle_action: Optional[any] = None - self.state = QueueState.IDLE - self.background_task = None + self.queue_task = asyncio.create_task(self.run_queue()) + self.idle_action_task = None async def run_queue(self): - while len(self.queued_actions) > 0: - self.state = QueueState.POPPING - action = self.queued_actions.pop(0) - - if action is None: - break - - await action[0](*(action[1]), **(action[2])) - - self.state = QueueState.IDLE - if self.idle_action: - await self.idle_action() - - async def stop_queue(self): - if self.background_task is None: - return - - self.state = QueueState.STOPPED - self.background_task.cancel() - - async def restart_queue(self): - await self.stop_queue() - self.background_task = asyncio.create_task(self.run_queue()) + try: + while True: + if self.queued_actions.empty() and self.idle_action is not None: + self.idle_action_task = asyncio.create_task(self.idle_action()) + + action = await self.queued_actions.get() + + if self.idle_action_task is not None: + self.idle_action_task.cancel() + self.idle_action_task = None + + if action is not None: # If none -> Is idle action update + await action[0](*(action[1]), **(action[2])) + + except: + pass async def add_action_to_queue(self, action, *args, **kwargs): - self.queued_actions.append((action, args, kwargs)) + await self.queued_actions.put((action, args, kwargs)) - if self.state == QueueState.IDLE: - await self.restart_queue() - - async def set_idle_action(self, action): - self.idle_action = action - - if self.state == QueueState.IDLE: - await self.restart_queue() + async def set_idle_action(self, action, *args, **kwargs): + self.idle_action = (action, args, kwargs) + await self.queued_actions.put(None) +