Schedule Asyncio task to execute every X seconds?

2019-07-25 17:59发布

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条回答
Luminary・发光体
2楼-- · 2019-07-25 18:46
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()
查看更多
登录 后发表回答