Skip to content

Instantly share code, notes, and snippets.

@myobie
Created February 17, 2020 21:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myobie/132bb06b59e7e218475cb9286761e393 to your computer and use it in GitHub Desktop.
Save myobie/132bb06b59e7e218475cb9286761e393 to your computer and use it in GitHub Desktop.
GCD Timer using DispatchSourceTimer that is much simpler
import Foundation
class Timer {
private let source: DispatchSourceTimer
private let block: () -> ()
public let isRepeating: Bool
init(_ interval: DispatchTimeInterval, repeat shouldRepeat: Bool = false, block: @escaping () -> ()) {
self.source = DispatchSource.makeTimerSource()
self.block = block
self.isRepeating = shouldRepeat
let deadline = DispatchTime.now().advanced(by: interval)
let repeating: DispatchTimeInterval = shouldRepeat ? interval : .never
source.schedule(deadline: deadline, repeating: repeating)
source.setEventHandler { [weak self] in self?.fire() }
source.activate()
}
private func fire() {
block()
if !isRepeating { source.cancel() }
}
deinit {
source.cancel()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment