Skip to content Skip to sidebar Skip to footer

@tasks.loop() Stopping Commands From Running Until The Loop Is Finished

I have a background loop involving selenium, so it takes a long time to finish executing. I noticed that the bot had a delay when responding to commands, and I found out that the p

Solution 1:

If you have long running code then you should move it into separated function and run it with threading or `multiprocessing.

Here basic example with threading. It runs new thread in every loop. For something more complex it may need different menthod. It may need to run single thread before discord and use queue in loop to send information to thread.

from discord.ext import commands, tasks
import time
import threading
import os

bot = commands.Bot(command_prefix='-')

@bot.command()
async def test(ctx):
    await ctx.send('hi')

def long_running_function():
    print('long_running_function: start')
    time.sleep(10)
    print('long_running_function: end')
    
@tasks.loop(seconds=30)
async def loop():
    print('h')
    t = threading.Thread(target=long_running_function)
    t.start()
    print('i')

@bot.event
async def on_ready():
    loop.start()

bot.run(os.getenv('DISCORD_TOKEN'))

Post a Comment for "@tasks.loop() Stopping Commands From Running Until The Loop Is Finished"