Waqas Abbasi
Waqas Abbasi

Reputation: 33

Start an async function inside a new thread

I'm trying to create a discord bot and I need to run an async function in another new Thread since the main Thread is required to run another function (Discord Client)

What I'm trying to accomplish:

# This methods needs to run in another thread
async def discord_async_method():
    while True:
        sleep(10)
        print("Hello World")
        ... # Discord Async Logic

# This needs to run in the main thread
client.run(TOKEN)

thread = ""

try:
    # This does not work, throws error "printHelloWorld Needs to be awaited"
    thread = Thread(target=discord_async_method)
    thread.start()
except (KeyboardInterrupt, SystemExit):

    # Stop Thread when CTRL + C is pressed or when program is exited
    thread.join()

I have tried other solutions with asyncio but I couldn't get the other solutions to work.

Followup: When you create a Thread, how do you stop that thread when you stop the program i.e. KeyboardInterupt or SystemExit?

Any help would be appreciated, Thank you!

Upvotes: 3

Views: 21094

Answers (2)

DenisKolodin
DenisKolodin

Reputation: 15071

This also works for me:

def entrypoint(*params):
    asyncio.run(discord_async_method(*params))

t = threading.Thread(target=entrypoint, args=(param,), daemon=True)

Upvotes: 7

user4815162342
user4815162342

Reputation: 154866

You don't need to involve threads to run two things in parallel in asyncio. Simply submit the coroutine to the event loop as a task before firing up the client.

Note that your coroutine must not run blocking calls, so instead of calling sleep() you need to await asyncio.sleep(). (This is generally the case with coroutines, not just ones in discord.)

async def discord_async_method():
    while True:
        await asyncio.sleep(10)
        print("Hello World")
        ... # Discord Async Logic

# run discord_async_method() in the "background"
asyncio.get_event_loop().create_task(discord_async_method())

client.run(TOKEN)

Upvotes: 9

Related Questions