python 异步操作如何控制超时

对于 Python 异步操作中的某一次请求,如果超时就中断它,同时保证其他请求仍正常执行,可以使用 asyncio.wait_for() 函数和 asyncio.shield() 函数来实现。

asyncio.wait_for() 函数用于等待异步操作完成,如果指定的超时时间内操作未完成,则抛出 asyncio.TimeoutError 异常。asyncio.shield() 函数可以保护正在进行的协程不会被取消,以防止一个操作的取消导致整个协程的取消。

以下是示例代码:

import asyncio
import time

async def fetch_url(url):
    print(f"Start fetching url {url}")
    await asyncio.sleep(2)
    print(f"Successfully fetched url {url}")
    return f"{url} content"

async def main():
    try:
        # 等待一秒,模拟请求超时
        result = await asyncio.wait_for(asyncio.shield(fetch_url('https://www.example.com')), timeout=1)
        print(f"Result: {result}")
    except asyncio.TimeoutError:
        print("Timeout reached, the request was cancelled")

    # 这个请求不会被影响
    result2 = await fetch_url('https://www.google.com')
    print(f"Result2: {result2}")

asyncio.run(main())

在上面的代码中,我们定义了一个 fetch_url() 异步函数来模拟向一个 URL 发起请求。然后我们在 main() 函数中使用asyncio.wait_for() 函数等待这个异步请求的完成,并采用 asyncio.shield() 函数保护这个异步请求免受取消的影响。在这个例子中,我们将超时时间设置为 1 秒钟,如果请求在 1 秒钟内完成,则正常打印结果;否则,超时并取消这个异步请求。在超时时,程序将继续执行其他的请求,并打印消息 “Timeout reached, the request was cancelled”。已经开始的请求不会受到影响。

注意,我们可以使用 asyncio.shield() 函数为任何异步操作提供保护,包括 asyncio.wait_for(),asyncio.gather() 和其他异步操作。

此外,正如前面的回答中所述,要对多个异步请求进行超时控制,可以将它们作为列表或可迭代对象传递给 asyncio.wait() 函数,然后使用 asyncio.shield() 函数保护当前正在进行的每个服务请求。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值