使用 run_in_executor 和 asyncio 时的超时处理

Timeout handling while using run_in_executor and asyncio

我正在使用 asyncio 运行 一段像这样的阻塞代码:

result = await loop.run_in_executor(None, long_running_function)

我的问题是:我可以为 long_running_function 的执行施加超时吗?

基本上我不希望 long_running_function 持续超过 2 秒并且我无法在其中进行适当的超时处理,因为该函数来自第三方库。

你可以使用 asyncio.wait_for:

future = loop.run_in_executor(None, long_running_function)
result = await asyncio.wait_for(future, timeout, loop=loop)

有关取消长 运行 函数的警告:

尽管用 asyncio.wait_for 调用包装 loop.run_in_executor 返回的 Future 将允许 事件循环 停止等待 long_running_function 一些 x 秒后,它不一定会停止基础 long_running_function。这是 concurrent.futures 的缺点之一,据我所知,没有简单的方法可以取消 concurrent.futures.Future.