Dino0040 fixes everthing

This commit is contained in:
Maximilian Giller 2024-01-30 19:58:21 +01:00
parent 931e7c1dc0
commit 1854c3ee27

View file

@ -1,54 +1,36 @@
import asyncio import asyncio
from typing import Optional 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: class ActionQueue:
def __init__(self) -> None: def __init__(self) -> None:
self.queued_actions: list = [] self.queued_actions: asyncio.Queue = asyncio.Queue()
self.idle_action: Optional[any] = None self.idle_action: Optional[any] = None
self.state = QueueState.IDLE self.queue_task = asyncio.create_task(self.run_queue())
self.background_task = None self.idle_action_task = None
async def run_queue(self): async def run_queue(self):
while len(self.queued_actions) > 0: try:
self.state = QueueState.POPPING while True:
action = self.queued_actions.pop(0) if self.queued_actions.empty() and self.idle_action is not None:
self.idle_action_task = asyncio.create_task(self.idle_action())
if action is None:
break action = await self.queued_actions.get()
await action[0](*(action[1]), **(action[2])) if self.idle_action_task is not None:
self.idle_action_task.cancel()
self.state = QueueState.IDLE self.idle_action_task = None
if self.idle_action:
await self.idle_action() if action is not None: # If none -> Is idle action update
await action[0](*(action[1]), **(action[2]))
async def stop_queue(self):
if self.background_task is None: except:
return pass
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())
async def add_action_to_queue(self, action, *args, **kwargs): 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: async def set_idle_action(self, action, *args, **kwargs):
await self.restart_queue() self.idle_action = (action, args, kwargs)
await self.queued_actions.put(None)
async def set_idle_action(self, action):
self.idle_action = action
if self.state == QueueState.IDLE:
await self.restart_queue()