【问题标题】:Python - run an async funtion after delay and do not block other codePython - 延迟后运行异步函数并且不阻塞其他代码
【发布时间】:2021-05-10 08:42:51
【问题描述】:

这是我的代码:

async def outer():
    # if this while loop was not broken in 5 seconds, do something
    while True:
        # some code with breaks
    

通常我需要一个非阻塞异步定时器。

【问题讨论】:

  • asyncio.sleep ?
  • @python_user 不是,它会阻止同一功能内的其他代码
  • 你的意思是如果outer没有在5秒内完成你需要做点什么吗?
  • @Ceres 不,我需要检查 while 的完成时间

标签: python asynchronous timer python-asyncio


【解决方案1】:
def outer():
    async def loop():
         #while loop here
  

    task = asyncio.create_task(loop())
    done, pending = await asyncio.wait([task], return_when=asyncio.FIRST_COMPLETED, timeout=5)
    if task in done:
        # loop has completed
    else:
       # loop is incomplete

参考资料:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多