ios - 子类化 OperationQueue 添加睡眠期
问题描述
import Foundation
class MyOperationQueue {
static let shared = MyOperationQueue()
private var queue: OperationQueue
init() {
self.queue = OperationQueue()
queue.name = "com.myqueue.name"
queue.maxConcurrentOperationCount = 1
queue.qualityOfService = .background
}
func requestDataOperation() {
queue.addOperation {
print("START NETWORK \(Date())")
NetworkService.shared.getData()
print("END NETWORK \(Date())")
}
}
func scheduleSleep() {
queue.cancelAllOperations()
queue.addOperation {
print("SLEEP START \(Date())")
Thread.sleep(forTimeInterval: 5)
print("SLEEP END \(Date())")
}
}
func cancelAll() {
queue.cancelAllOperations()
}
}
我requestDataOperation
每隔 10 秒将函数放入一个计时器中。我有一个按钮可以scheduleSleep
手动调用。当我点击按钮时,我预计每隔 5 秒就会对请求进行去抖动处理。
但我得到这样的东西:
START NETWORK
END NETWORK
SLEEP START 2021-03-11 11:13:40 +0000
SLEEP END 2021-03-11 11:13:45 +0000
SLEEP START 2021-03-11 11:13:45 +0000
SLEEP END 2021-03-11 11:13:50 +0000
START NETWORK
END NETWORK
自上次点击后如何增加 5 秒并将其组合在一起而不是将其分成两个操作?我打电话queue.cancelAllOperations
并开始新的睡眠操作,但似乎不起作用。
预期结果:
START NETWORK
END NETWORK
SLEEP START 2021-03-11 11:13:40 +0000
// <- the second tap when 2 seconds passed away
SLEEP END 2021-03-11 11:13:47 +0000 // 2+5
START NETWORK
END NETWORK
解决方案
如果您希望某些操作延迟一定的时间,我不会创建“队列”类,而是只定义一个直到该时间过去(例如,5 秒后)才会出现Operation
的类。isReady
这不仅消除了对两个单独的“睡眠操作”的需要,而且完全消除了它们。
例如,
class DelayedOperation: Operation {
@Atomic private var enoughTimePassed = false
private var timer: DispatchSourceTimer?
private var block: (() -> Void)?
override var isReady: Bool { enoughTimePassed && super.isReady } // this operation won't run until (a) enough time has passed; and (b) any dependencies or the like are satisfied
init(timeInterval: TimeInterval = 5, block: @escaping () -> Void) {
self.block = block
super.init()
resetTimer(for: timeInterval)
}
override func main() {
block?()
block = nil
}
func resetTimer(for timeInterval: TimeInterval = 5) {
timer = DispatchSource.makeTimerSource() // create GCD timer (eliminating reference to any prior timer will cancel that one)
timer?.setEventHandler { [weak self] in
guard let self = self else { return }
self.willChangeValue(forKey: #keyPath(isReady)) // make sure to do necessary `isReady` KVO notification
self.enoughTimePassed = true
self.didChangeValue(forKey: #keyPath(isReady))
}
timer?.schedule(deadline: .now() + timeInterval)
timer?.resume()
}
}
我正在enoughTimePassed
与以下属性包装器同步我的交互,但您可以使用任何您想要的同步机制:
@propertyWrapper
struct Atomic<Value> {
private var value: Value
private var lock = NSLock()
init(wrappedValue: Value) {
value = wrappedValue
}
var wrappedValue: Value {
get { synchronized { value } }
set { synchronized { value = newValue } }
}
private func synchronized<T>(block: () throws -> T) rethrows -> T {
lock.lock()
defer { lock.unlock() }
return try block()
}
}
只要确保这isReady
是线程安全的。
无论如何,已经定义了DelayedOperation
,那么你可以做类似的事情
logger.debug("creating operation")
let operation = DelayedOperation {
logger.debug("some task")
}
queue.addOperation(operation)
并且它将延迟运行该任务(在这种情况下,只需登录“某些任务”消息)五秒钟。如果要重置计时器,只需在操作子类上调用该方法:
operation.resetTimer()
例如,这里我创建了任务,将其添加到队列中,以两秒的时间间隔将其重置 3 次,并且该块实际上在最后一次重置后运行了 5 秒:
2021-09-30 01:13:12.727038-0700 MyApp[7882:228747] [ViewController] creating operation
2021-09-30 01:13:14.728953-0700 MyApp[7882:228747] [ViewController] delaying operation
2021-09-30 01:13:16.728942-0700 MyApp[7882:228747] [ViewController] delaying operation
2021-09-30 01:13:18.729079-0700 MyApp[7882:228747] [ViewController] delaying operation
2021-09-30 01:13:23.731010-0700 MyApp[7882:228829] [ViewController] some task
现在,如果您正在对网络请求使用操作,那么您可能已经实现了自己的异步子类,该子类为、等Operation
执行必要的 KVO ,因此您可以选择将上述逻辑与现有子类结合起来。isFinished
isExecuting
isReady
Operation
但是这个想法是一个可以完全失去异步模式的“睡眠”操作。如果您确实想要一个专用的睡眠操作,您仍然可以使用上述模式(但使其成为异步操作,而不是用 阻塞线程sleep
)。
说了这么多,如果我个人想要对网络请求进行去抖动,我不会将它集成到操作或操作队列中。我会在开始请求时进行去抖动:
weak var timer: Timer?
func debouncedRequest(in timeInterval: TimeInterval = 5) {
timer?.invalidate()
timer = .scheduledTimer(withTimeInterval: timeInterval, repeats: false) { _ in
// initiate request here
}
}
推荐阅读
- javascript - 在 firebase 的反应组件中显示用户名
- azure-iot-sdk - Azure IoT SDK - 对直接方法的异步响应
- ruby - 如何在 Ruby 中创建一个取数组平均值的函数?
- apache-spark - pyspark - spark 如何为 Python 解释器设置 *NIX 进程
- javascript - 如何将消息保存在变量中,以后再删除?
- visual-studio - 错误:“项目不知道如何运行配置文件 IIS Express”(VS 2019、16.10.1)
- python - multiprocessing 的返回值,作为 python 中另一个函数的输入
- c# - 在中间件中,为什么这个值只设置一次?
- sql - 如何在 laravel 8 中使用 groupby 获取 SQL 的第一行?
- json - 在 ocaml 中解析 json