python - asyncio:发生异常时如何对对象进行排队
问题描述
嗨,我必须同时处理几个排队 5 的对象。我有一个包含 5 个项目的队列。有时进程失败并发生异常:
async def worker(nam):
while True:
queue_item = await queue.get()
Worker 启动流程循环并尝试处理项目
try:
loop = asyncio.get_event_loop()
task = loop.create_task(download(queue_item, path))
download_result = await asyncio.wait_for(task, timeout=timeout)
except asyncio.TimeoutError:
不幸的是,该过程超时。我可以这样添加吗?
except asyncio.TimeoutError:
await queue.put(queue_item)
我想在下一轮再次处理该项目 谢谢
解决方案
是的,您可以在队列末尾重新排列对象以进行处理。基于您的代码的简单示例:
import asyncio
from random import randrange
async def download(item):
print("Process item", item)
if randrange(4) == 1: # simulate occasional event
await asyncio.sleep(100) # trigger timeout error
async def worker(queue):
while True:
queue_item = await queue.get()
try:
result = await asyncio.wait_for(download(queue_item), timeout=1)
except asyncio.TimeoutError:
print("Timeout for ", queue_item)
await queue.put(queue_item)
queue.task_done()
async def main():
q = asyncio.Queue()
asyncio.create_task(worker(q))
for i in range(5): # put 5 items to process
await q.put(i)
await q.join()
asyncio.run(main())
Process item 0
Timeout for 0
Process item 1
Process item 2
Process item 3
Timeout for 3
Process item 4
Process item 0
Process item 3
推荐阅读
- docker - 使用 docker-compose 的 Pycharm 远程解释器无法在调试模式下工作
- security - 如何使用给定的哈希函数和一些参数计算 MAC 的密钥?
- java - 为什么这不会画一个直的矩形?
- python - Python MySQL 错误 1210:执行准备好的语句的参数数量不正确
- javascript - 无法使用通过 ng-if 创建的子范围设置父变量
- sql - SQL - 生成没有列名的 JSON 数组
- angular - ionSlides 未定义
- javascript - Vuex 返回“TypeError:无法读取未定义的属性‘getters’”
- database - 由于雪花中的权限,无法克隆数据库
- regex - 必应搜索链接到 Google 表格中的基础链接