【问题标题】:Do a task for a 1 minute interval telethon为 1 分钟间隔的电视马拉松做一项任务
【发布时间】: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分钟运行一次上面的代码,我该如何实现?

【问题讨论】:

    标签: python bots telethon


    【解决方案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())
    

    【讨论】:

      【解决方案2】:

      我们使用循环,为了多次执行同一个任务,可以考虑使用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。
      • @Lonami 我的错! OP 想要多次执行相同的任务,所以我更专注于循环,顺便说一句,我已经编辑了我的答案:)
      猜你喜欢
      • 1970-01-01
      • 2022-09-27
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-28
      相关资源
      最近更新 更多