Start an async function inside a new thread

試著忘記壹切 提交于 2021-02-05 12:17:23

问题


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!


回答1:


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)


来源:https://stackoverflow.com/questions/61151031/start-an-async-function-inside-a-new-thread

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