在一个新线程中启动一个异步函数



我正在尝试创建一个discord bot,我需要在另一个新线程中运行异步函数,因为主线程需要运行另一个函数(discord Client(

我正在努力实现的目标:

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

这也适用于我:

def entrypoint(*params):
asyncio.run(discord_async_method(*params))
t = threading.Thread(target=entrypoint, args=(param,), daemon=True)

最新更新