我正在尝试创建一个 discord 机器人,我需要在另一个新线程中运行一个异步函数,因为主线程需要运行另一个函数(Discord 客户端)
我要实现的目标:
# 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()
我尝试过使用 asyncio 的其他解决方案,但我无法让其他解决方案起作用。
跟进:创建线程时,如何在停止程序(即 KeyboardInterupt 或 SystemExit)时停止该线程?
如有任何帮助,我们将不胜感激,谢谢!
最佳答案
在 asyncio 中,你不需要让线程来并行运行两个东西。在启动客户端之前,只需将协程作为任务提交到事件循环。
请注意,您的协程不得运行阻塞调用,因此您需要等待 asyncio.sleep()
而不是调用 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)
关于python - 在新线程中启动异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61151031/