這是小專欄《完全搞定 GCD🚦併發編程》的一篇副產品文章ios
Repeat 是 Daniele 開發的一個基於 GCD - Grand Central Dispatch 的輕量定時器,可用於替代 NSTimer
,解決其多項不足。git
Daniel 着重強調的一些特性:github
針對以上特性,咱們接下來閱讀源碼時能夠着重看看 Daniel 是怎樣實現的。shell
另外,這個庫還擴展提供了兩個有趣的特性:編程
這兩個特性對於用過 RxSwift
的開發者確定不陌生,有了定時器,實現這二者也是瓜熟蒂落。swift
首先,從接口的設計來看看其是否「簡潔明瞭」、「不冗餘」,再逐步深刻其內部實現。api
注意:
Repeater
被設計成和其餘許多對象同樣,須要被持有來避免被釋放。xcode
// 建立單次執行定時器
log("當時只道是尋常")
self.timer = Repeater.once(after: .seconds(5)) { timer in
// 5s 後運行
log("歲月如歌,簡單愛一次")
}
複製代碼
輸出:併發
2019-10-14 15:12:04 +0000: 當時只道是尋常
2019-10-14 15:12:09 +0000: 歲月如歌,簡單愛一次
複製代碼
func test_timer_once() {
let exp = expectation(description: "test_once")
let timer = Repeater.once(after: .seconds(5)) { _ in
exp.fulfill()
}
print("Allocated timer \(timer)")
wait(for: [exp], timeout: 6)
}
複製代碼
log("當時只道是尋常")
self.timer = Repeater.every(.seconds(10), count: 5) { timer in
// 每 10s 運行 1 次,5 次後結束
log("歲月如歌,簡單愛一次")
}
複製代碼
輸出:app
2019-10-14 15:18:56 +0000: 當時只道是尋常
2019-10-14 15:19:06 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:19:16 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:19:26 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:19:36 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:19:46 +0000: 歲月如歌,簡單愛一次
複製代碼
func test_timer_finiteAndRestart() {
let exp = expectation(description: "test_finiteAndRestart")
var count: Int = 0
var finishedFirstTime: Bool = false
let timer = Repeater(interval: .seconds(0.5), mode: .finite(5)) { _ in
count += 1
print("Iteration #\(count)")
}
timer.onStateChanged = { (_, state) in
print("State changed: \(state)")
if state.isFinished {
if finishedFirstTime == false {
print("Now restart")
timer.start()
finishedFirstTime = true
} else {
exp.fulfill()
}
}
}
timer.start()
wait(for: [exp], timeout: 30)
}
複製代碼
單元測試輸出:
State changed: running
State changed: executing
Iteration #1
State changed: executing
Iteration #2
State changed: executing
Iteration #3
State changed: executing
Iteration #4
State changed: executing
Iteration #5
State changed: finished
Now restart
State changed: idle/paused
State changed: running
State changed: executing
Iteration #6
State changed: executing
Iteration #7
State changed: executing
Iteration #8
State changed: executing
Iteration #9
State changed: executing
Iteration #10
State changed: finished
複製代碼
能夠看到,有限次的定時器在次數達到結束後,還能夠繼續調用 start()
從新開始再次複用,而沒必要另外建立新實例。
log("當時只道是尋常")
let timer = Repeater.every(.seconds(5)) { timer in
// 每 5s 運行一次,直到 timer 生命週期結束
log("歲月如歌,簡單愛一次")
}
複製代碼
輸出:
2019-10-14 15:24:05 +0000: 當時只道是尋常
2019-10-14 15:24:10 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:24:15 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:24:20 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:24:25 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:24:30 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:24:35 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:24:40 +0000: 歲月如歌,簡單愛一次
2019-10-14 15:24:45 +0000: 歲月如歌,簡單愛一次
...
複製代碼
func test_timer_infinite() {
let exp = expectation(description: "test_once")
var count: Int = 0
let timer = Repeater.every(.seconds(0.5), { _ in
count += 1
if count == 20 {
exp.fulfill()
}
})
print("Allocated timer \(timer)")
wait(for: [exp], timeout: 10)
}
複製代碼
log("當時只道是尋常")
self.timer = Repeater(interval: .seconds(5), mode: .infinite) { _ in
// 每 5s 運行一次,直到 timer 生命週期結束
log("歲月如歌,簡單愛一次")
}
timer.start()
複製代碼
輸出:
2019-10-14 23:13:46 +0000: 當時只道是尋常
2019-10-14 23:13:51 +0000: 歲月如歌,簡單愛一次
2019-10-14 23:13:56 +0000: 歲月如歌,簡單愛一次
2019-10-14 23:14:01 +0000: 歲月如歌,簡單愛一次
2019-10-14 23:14:06 +0000: 歲月如歌,簡單愛一次
2019-10-14 23:14:11 +0000: 歲月如歌,簡單愛一次
2019-10-14 23:14:16 +0000: 歲月如歌,簡單愛一次
2019-10-14 23:14:21 +0000: 歲月如歌,簡單愛一次
2019-10-14 23:14:26 +0000: 歲月如歌,簡單愛一次
...
複製代碼
其餘方法:
start()
: 開始一個已暫停或新建立的定時器pause()
:暫停一個正在運行的定時器reset(_ interval: Interval, restart: Bool)
:重置一個正在運行的定時器,更改時間間隔並從新開始fire()
:額外手動調用一次定時器綁定事件屬性:
.mode
:定時器類型模式
infinite
:無限定時重複finite
:有限次定時重複once
:單次定時執行.remainingIterations
:針對 .finite
有限次重複模式結束前的剩餘迭代次數通常而言,初始化定時器時會指定一個處理方法。除此以外, Repeat 的定時器還支持經過observe()
額外添加處理方法,而且支持經過token
再移除。
// 添加額外的處理監聽
let token = timber.observe { _ in
// 額外的新處理
log("一個鬧鐘可以同時叫醒相愛的兩我的。")
}
timer.start()
// 移除
timer.remove(token)
複製代碼
每一個定時器維護着一個狀態機,處在如下某個狀態:
.paused
:空閒(未被開始過)或已暫停.running
:正在計時中.executing
:註冊的定時處理方法正在執行.finished
:計時結束能夠經過.onStateChanged
屬性添加狀態變化回調監聽:
timer.onStateChanged = { timer, newState in
// 觀察定時器狀態變化並作相應處理
log("你永遠叫不醒一個裝睡的人")
}
複製代碼
TBD
TBD
接下來,進一步看看以上的接口都是如何實現的吧。
.
├── CHANGELOG.md
├── Configs
│ ├── Repeat.plist
│ └── RepeatTests.plist
├── LICENSE
├── Package.swift
├── README.md
├── Repeat.podspec
├── Repeat.xcodeproj
├── Sources
│ └── Repeat
│ ├── Debouncer.swift
│ ├── Repeater.swift
│ └── Throttler.swift
└── Tests
├── LinuxMain.swift
└── RepeatTests
└── RepeatTests.swift
複製代碼
主要文件:
Timer
的異同在接口設計與使用中能夠看到,Repeater 提供了便捷工廠類方法,而且生成的定時器都會「自動開始」,與 Timer
的工廠類方法類似:
/// Alternative API for timer creation with a block.
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative to creation via selector
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
/// - Warning: Capturing the timer or the owner of the timer inside of the block may cause retain cycles. Use with caution
open class func scheduledTimer(withTimeInterval interval: TimeInterval, repeats: Bool, block: @escaping (Timer) -> Void) -> Timer {
let timer = Timer(fire: Date(timeIntervalSinceNow: interval), interval: interval, repeats: repeats, block: block)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer._timer!, kCFRunLoopDefaultMode)
return timer
}
複製代碼
👆Tips & Declaration: Timer.swift,註釋中有特別提醒注意循環引用的問題。
對比一下 Repeater
的類工廠方法實現:
/// Create and schedule a timer that will call `handler` once after the specified time.
///
/// - Parameters:
/// - interval: interval delay for single fire
/// - queue: destination queue, if `nil` a new `DispatchQueue` is created automatically.
/// - observer: handler to call when timer fires.
/// - Returns: timer instance
@discardableResult
public class func once(after interval: Interval, tolerance: DispatchTimeInterval = .nanoseconds(0), queue: DispatchQueue? = nil, _ observer: @escaping Observer) -> Repeater {
let timer = Repeater(interval: interval, mode: .once, tolerance: tolerance, queue: queue, observer: observer)
timer.start()
return timer
}
/// Create and schedule a timer that will fire every interval optionally by limiting the number of fires.
///
/// - Parameters:
/// - interval: interval of fire
/// - count: a non `nil` and > 0 value to limit the number of fire, `nil` to set it as infinite.
/// - queue: destination queue, if `nil` a new `DispatchQueue` is created automatically.
/// - handler: handler to call on fire
/// - Returns: timer
@discardableResult
public class func every(_ interval: Interval, count: Int? = nil, tolerance: DispatchTimeInterval = .nanoseconds(0), queue: DispatchQueue? = nil, _ handler: @escaping Observer) -> Repeater {
let mode: Mode = (count != nil ? .finite(count!) : .infinite)
let timer = Repeater(interval: interval, mode: mode, tolerance: tolerance, queue: queue, observer: handler)
timer.start()
return timer
}
複製代碼
二者的作法截然不同,都是建立一個定時器實例並「自動開始」,只是開始的方式因爲內部固有的實現方式有所不一樣:
Timer
依賴 RunLoop
,須要將建立定時器生成的 CFRunLoopTimer
加入當前 Runloop
Repeater
依賴 GCD 的 DispatchSourceTimer
,start
內部會調 DispatchSourceTimer
的 實例方法resume
/// Initialize a new timer.
///
/// - Parameters:
/// - interval: interval of the timer
/// - mode: mode of the timer
/// - tolerance: tolerance of the timer, 0 is default.
/// - queue: queue in which the timer should be executed; if `nil` a new queue is created automatically.
/// - observer: observer
public init(interval: Interval, mode: Mode = .infinite, tolerance: DispatchTimeInterval = .nanoseconds(0), queue: DispatchQueue? = nil, observer: @escaping Observer) {
self.mode = mode
self.interval = interval
self.tolerance = tolerance
self.remainingIterations = mode.countIterations
self.queue = (queue ?? DispatchQueue(label: "com.repeat.queue"))
self.timer = configureTimer()
self.observe(observer)
}
複製代碼
初始化方法參數列表:
interval
:定時器時間間隔mode
:定時器重複模式,默認爲.infinite
,無限重複tolerance
:允許偏差(這個最終是做爲DispatchSourceTimer
的leeway
參數)queue
:指定定時器運行的隊列,若未指定,則自動建立默認隊列observer
:定時器運行的回調方法private func configureTimer() -> DispatchSourceTimer {
let associatedQueue = (queue ?? DispatchQueue(label: "com.repeat.\(NSUUID().uuidString)"))
let timer = DispatchSource.makeTimerSource(queue: associatedQueue)
let repeatInterval = interval.value
let deadline: DispatchTime = (DispatchTime.now() + repeatInterval)
if self.mode.isRepeating {
timer.schedule(deadline: deadline, repeating: repeatInterval, leeway: tolerance)
} else {
timer.schedule(deadline: deadline, leeway: tolerance)
}
timer.setEventHandler { [weak self] in
if let unwrapped = self {
unwrapped.timeFired()
}
}
return timer
}
複製代碼
timeFired
方法處理這一段代碼是 Repeat 中 GCD 的應用關鍵,Repeat 的核心計時器便是 DispatchSourceTimer,進一步封裝並屏蔽部分複雜邏輯,以提供簡潔易用的接口。
/// Reset the state of the timer, optionally changing the fire interval.
///
/// - Parameters:
/// - interval: new fire interval; pass `nil` to keep the latest interval set.
/// - restart: `true` to automatically restart the timer, `false` to keep it stopped after configuration.
public func reset(_ interval: Interval?, restart: Bool = true) {
if self.state.isRunning {
self.setPause(from: self.state)
}
// For finite counter we want to also reset the repeat count
if case .finite(let count) = self.mode {
self.remainingIterations = count
}
// Create a new instance of timer configured
if let newInterval = interval {
self.interval = newInterval
} // update interval
self.destroyTimer()
self.timer = configureTimer()
self.state = .paused
if restart {
self.timer?.resume()
self.state = .running
}
}
/// Start timer. If timer is already running it does nothing.
@discardableResult
public func start() -> Bool {
guard self.state.isRunning == false else {
return false
}
// If timer has not finished its lifetime we want simply
// restart it from the current state.
guard self.state.isFinished == true else {
self.state = .running
self.timer?.resume()
return true
}
// Otherwise we need to reset the state based upon the mode
// and start it again.
self.reset(nil, restart: true)
return true
}
/// Pause a running timer. If timer is paused it does nothing.
@discardableResult
public func pause() -> Bool {
guard state != .paused && state != .finished else {
return false
}
return self.setPause(from: self.state)
}
/// Pause a running timer optionally changing the state with regard to the current state.
///
/// - Parameters:
/// - from: the state which the timer should only be paused if it is the current state
/// - to: the new state to change to if the timer is paused
/// - Returns: `true` if timer is paused
@discardableResult
private func setPause(from currentState: State, to newState: State = .paused) -> Bool {
guard self.state == currentState else {
return false
}
self.timer?.suspend()
self.state = newState
return true
}
複製代碼
start
方法主要是作狀態判斷並進行相應處理返回結果,其開始計時的核心是調用內部 DispatchSourceTimer
的 resume
方法pause
方法相似,調用的是 suspend
方法,並更新內部計時器狀態reset
重置內部的一些計時標誌位的同時,會將內部的 DispatchSourceTimer
銷燬並新建/// List of the observer of the timer
private var observers = [ObserverToken: Observer]()
/// Next token of the timer
private var nextObserverID: UInt64 = 0
/// Add new a listener to the timer.
///
/// - Parameter callback: callback to call for fire events.
/// - Returns: token used to remove the handler
@discardableResult
public func observe(_ observer: @escaping Observer) -> ObserverToken {
var (new, overflow) = self.nextObserverID.addingReportingOverflow(1)
if overflow { // you need to add an incredible number of offset...sure you can't
self.nextObserverID = 0
new = 0
}
self.nextObserverID = new
self.observers[new] = observer
return new
}
/// Remove an observer of the timer.
///
/// - Parameter id: id of the observer to remove
public func remove(observer identifier: ObserverToken) {
self.observers.removeValue(forKey: identifier)
}
複製代碼
/// Called when timer is fired
private func timeFired() {
self.state = .executing
if case .finite = self.mode {
self.remainingIterations! -= 1
}
// dispatch to observers
self.observers.values.forEach { $0(self) }
// manage lifetime
switch self.mode {
case .once:
// once timer's lifetime is finished after the first fire
// you can reset it by calling `reset()` function.
self.setPause(from: .executing, to: .finished)
case .finite:
// for finite intervals we decrement the left iterations count...
if self.remainingIterations! == 0 {
// ...if left count is zero we just pause the timer and stop
self.setPause(from: .executing, to: .finished)
}
case .infinite:
// infinite timer does nothing special on the state machine
break
}
}
複製代碼
timeFired
方法被兩個地方調用,一個是配置DispatchSourceTimer
時設置的事件回調,一個是對外暴露的手動觸發方法 fire(andPause:)
中文中涉及源碼大部分來自開源社區,以及部分其餘文獻參考。
Repeat by Daniele Margutti, under The MIT License (MIT)
swift-corelibs-foundation Licensed under Apache License v2.0 with Runtime Library Exception
A Background Repeating Timer in Swift by Daniel Galasko