【发布时间】:2021-10-27 23:42:36
【问题描述】:
我有一个问题,我不太确定如何做到这一点。我尽力搜索,但不知道(除了一段时间的真正任务)我怎么能做到这一点,我想要什么。所以我目前有一个带有messages 的列表,我的python 机器人需要从服务器X 传输到许多其他服务器(如队列系统)。
那么我的任务应该怎么做?我需要类似“实时”(async) 任务,它每次都会检查列表中的新条目。如果列表中没有任何内容,它应该等待新项目。我尝试了 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: 任务,我认为这对我的机器人性能不是很有效,没有await asyncio.sleep() 我什至无法启动机器人。
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: 任务并且可以使用更有效的方式呢?
重要提醒:因为它是一个队列系统,所以应该不可能运行两次任务。
【问题讨论】:
-
while True/sleep(1)的概念是不错的选择,但您可以在这里使用asyncio.Event。 Queue 进程发出事件信号,while循环等待它。 -
我怎么能做出这样的事情?
-
您可以阅读
asyncio.Event上的文档。 docs.python.org/3/library/asyncio-sync.html -
事件与此无关!!你需要一个队列。
-
队列函数被定义为异步,但它没有等待。它可能只是一个简单的函数。
标签: python python-3.x list task