安排Asyncio任务每X秒执行一次? [英] Schedule Asyncio task to execute every X seconds?
问题描述
我正在尝试创建一个python discord机器人,该机器人将每隔X秒检查一次活跃成员,并为他们的在线时间奖励积分。我正在使用asyncio处理聊天命令,并且一切正常。我的问题是找到一种方法来安排使用异步每隔X秒对活动成员进行一次检查
I'm trying to create a python discord bot that will check active members every X seconds, and award members with points for their time online. I'm using asyncio to handle the chat commands and that is all working. My issue is finding a way to schedule this checking of active members every X seconds with async
我已经阅读了asnycio文档,但这是我第一次使用它,并且我很难把头放在任务,循环和协同例程等上。
I've read the asnycio documentation but this is my first time working with it and I'm having a hard time wrapping my head around tasks and loops and co routines and etc.
@client.event
async def on_message(message):
# !gamble command
if message.content.startswith('!gamble'):
...code that works....
# !help command
elif message.content == '!help':
...code that works....
# !balance command
elif message.content == '!balance':
...code that works....
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
# Do this every X seconds to give online users +1 points
async def periodic_task():
TODO
我的目标是让机器人能够处理通过聊天发送给它的命令,同时每X秒触发一次与Discord服务器中的聊天命令或事件无关的功能。我知道如何使函数中的代码实现我的目标,而不是如何触发
My goal is to have the bot be able to handle commands given to it through chat, while also triggering a function every X seconds unrelated to chat commands or events in the Discord server. I know how to make the code inside the function achieve my goal, just not how to trigger it
推荐答案
async def do_stuff_every_x_seconds(timeout, stuff):
while True:
await asyncio.sleep(timeout)
await stuff()
并将其添加到循环中。
task = asyncio.create_task(do_stuff_every_x_seconds(10, stuff))
当您不再想要这样做时,
When you no longer want to do that,
task.cancel()
这篇关于安排Asyncio任务每X秒执行一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!