python - 将异步函数传递给线程python
问题描述
我正在构建一个 Discord 机器人,其中大部分是基于事件的。机器人准备好后,我想要一个线程,当机器人还活着时,有时会在聊天中写“嗨”,然后休眠 2 分钟。代码:
async def on_ready(self):
t = threading.Thread(target=self.say_hi)
t.start()
async def say_hi(self):
while True:
chance = random.randint(0, 101)
if chance <= 25:
await self.channel.send('hi')
time.sleep(60 * 2)
问题是我得到不同的错误。RuntimeWarning: Enable tracemalloc to get the object allocation traceback
在这种情况下。我尝试按照这个有点相关的答案以这种方式编辑代码:
def say_hi(self):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(self.say_hi_aux())
loop.close()
async def say_hi_aux(self):
while True:
chance = random.randint(0, 101)
if chance <= 25:
await self.channel.send('hi')
await asyncio.sleep(60 * 2)
但由此产生的错误RuntimeError: Timeout context manager should be used inside a task
在loop.run_until_complete()
方法上。
我不知道这两种解决方案有什么问题
解决方案
推荐阅读
- asp.net - Ajaxtoolkit - Autocomplete dont do anything when i click
- sql - SQL中“GO”语句的真正作用?
- python - 用另一个数据帧处理一个数据帧
- python - Dask 在应用函数中使用广播的 pandas.DataFrame
- c# - How to Rotate camera only in X-axis with mouse click and drag?
- c# - 我们可以为 Azure Redis 缓存中的所有键设置过期时间吗?
- javascript - 当其高度响应时,粘性标题会中断
- excel - 我的字符串提取代码有修复吗?
- python - Want to split the array element in 10 Chunks based on min and max element in a array
- android - 如何将 onClick 的 androidx-databinding 绑定到带参数的静态方法