Schedule Asyncio task to execute every X seconds?

自闭症网瘾萝莉.ら 提交于 2019-12-24 07:26:39

问题


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

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

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


回答1:


async def do_stuff_every_x_seconds(timeout, stuff):
    while True:
        await asyncio.sleep(timeout)
        await stuff()

And add this to loop.

task = asyncio.create_task(do_stuff_every_x_seconds(10, stuff))

When you no longer want to do that,

task.cancel()


来源:https://stackoverflow.com/questions/54153332/schedule-asyncio-task-to-execute-every-x-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!