问题
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