【发布时间】:2022-01-02 13:57:10
【问题描述】:
async def main():
me = await client.get_me()
await client.send_message(####, 'Hello')
with client:
client.loop.run_until_complete(main())
我想每1分钟运行一次上面的代码,我该如何实现?
【问题讨论】:
async def main():
me = await client.get_me()
await client.send_message(####, 'Hello')
with client:
client.loop.run_until_complete(main())
我想每1分钟运行一次上面的代码,我该如何实现?
【问题讨论】:
这是使用asyncio sleep 的一种解决方案:
from asyncio import sleep
async def main():
while True:
me = await client.get_me()
await client.send_message(####, 'Hello')
await sleep(60) # sleep for a min
with client:
client.loop.run_until_complete(main())
【讨论】:
我们使用循环,为了多次执行同一个任务,可以考虑使用while循环。
import asyncio
async def main():
me = await client.get_me()
while True: # True will make sure loop will run infinite time
await client.send_message("me", 'Hello')
await asyncio.sleep(60) # `.sleep` will make your code sleep for x ammout of seconds.
with client:
client.loop.run_until_complete(main())
【讨论】:
await 不能放在async def 之外,而且asyncio.sleep 需要await'ed。