我必须运行 1000 次异步计算。由于 API 有 50 个请求/分钟的限制,我必须将其分成 50 个块,并在处理一次块后等待一分钟。最终我想打印结果。
resultsArray = [Double]()
// chunked is an extension
points.chunked(into: 50).forEach { pointsChunk in
pointsChunk.forEach { pointsPair
// this function is async
service.calculate(pointsPair) { result in
resultsArray.append(result)
}
}
// wait for a minute before continuing with the next chunk
}
// after all 1000 calculations are done, print result
print(resultsArray)
我确实尝试使用 using 找到解决方案,DispatchGroup
但在如何合并计时器方面遇到了困难:
let queue = DispatchQueue(label: "MyQueue", attributes: .concurrent)
let chunkGroup = DispatchGroup()
let workGroup = DispatchGroup()
points.chunked(into: 50).forEach { pointsChunk in
chunkGroup.enter()
pointsChunk.forEach { routePointsPair in
workGroup.enter()
// do something async and in the callback:
workGroup.leave()
}
workGroup.notify(queue: queue) {
do { sleep(60) }
chunkGroup.leave()
}
}
chunkGroup.notify(queue: .main) {
print(resultArray)
}
这只是一次执行所有块,而不是延迟 60 秒。