我如何创建一个任务,检查列表上的实时变化?



我有一个问题,我不太确定我怎么能做到这一点。我尽了最大的努力去搜索,但不知道(除了一个短暂的真实任务)我该怎么做,我想要什么。所以我目前有一个messages列表,我的python bot需要从服务器X转移到许多其他(如队列系统)。

那么我的任务应该做什么呢?我需要一些像"生活"这样的东西。(异步)任务,每次检查列表中是否有新条目。如果列表中不再有任何内容,则应该等待新条目。我尝试了一个while True:任务,但我认为这对我的机器人的性能来说不是一个好主意。

这是我当前查看/编辑队列的函数:

global_queue = []
async def Queue(action=None, globalmsg=None, original=None, code=None):
if action is not None:
if action == "add":
global_queue.append((globalmsg, original, code))
elif action == "remove":
global_queue.remove((globalmsg, original, code))
else:
return global_queue

这是我的while True:任务,我认为这对我的bot性能不是很有效,我甚至不能启动没有await asyncio.sleep()的bot。

def __init__(self, client):
self.client = client
client.loop.create_task(self.on_queue())
async def on_queue(self):
await self.client.wait_until_ready()
while True:
await asyncio.sleep(1)
queue = await Queue()
if len(queue) >= 1:
await Queue("remove", item[0], item[1], item[2])
# do something

那么我如何摆脱while True:任务,可以使用更有效的方式?重要提示:因为它是一个队列系统,所以不可能

您要找的是队列!

ayncio使用。队列而不是列表。

创建队列使用:

queue = asyncio.Queue()

将一个项目放入队列,使用:

await queue.put(item)

从队列中获取和删除一个项目:

item = await queue.get()

还是

await queue.get()

如果你不需要这个项目

如果队列为空,则任务被挂起,直到出现某个项目。如果您希望队列具有最大大小,请将最大大小作为参数传递给构造函数。然后,如果队列已满,则put()调用也会挂起任务,直到队列中有空间为止。

你可以阅读asyncio文档,但它不是很友好。我想去找一些教程。

最新更新