在新线程中启动异步函数

Waq*_*asi 3 python multithreading python-3.x async-await python-asyncio

我正在尝试创建一个不和谐机器人,我需要在另一个新线程中运行异步函数,因为主线程需要运行另一个函数(不和谐客户端)

我正在努力实现的目标:

# 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()

Run Code Online (Sandbox Code Playgroud)

我尝试过使用 asyncio 的其他解决方案,但无法让其他解决方案发挥作用。

后续:当您创建一个线程时,当您停止程序(即KeyboardInterupt或SystemExit)时,如何停止该线程?

任何帮助将不胜感激,谢谢!

use*_*342 9

您不需要涉及线程来在 asyncio 中并行运行两件事。只需在启动客户端之前将协程作为任务提交到事件循环即可。

请注意,您的协程不得运行阻塞调用,因此sleep()您需要等待而不是调用asyncio.sleep()。(这通常是协程的情况,而不仅仅是不和谐的协程。)

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)
Run Code Online (Sandbox Code Playgroud)