问题描述
我正在尝试创建一个不和谐的机器人,我需要在另一个新线程中运行一个异步函数,因为需要主线程才能运行另一个函数(Discord Client)
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)
我要完成的工作:
# 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的其他解决方案,但无法使用其他解决方案.
I have tried other solutions with asyncio but I couldn't get the other solutions to work.
后续活动:创建线程时,如何在停止程序(例如KeyboardInterupt或SystemExit)时停止该线程?
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!
推荐答案
您不需要让线程在asyncio中并行运行两件事.只需在启动客户端之前将协程作为任务提交给事件循环即可.
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.
请注意,您的协程一定不能运行阻塞调用,因此您需要等待 asyncio.sleep()
,而不是调用 sleep()
.(协程通常就是这种情况,而不仅仅是不和谐的协程.)
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)
这篇关于在新线程中启动异步功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!