Skip to content

Instantly share code, notes, and snippets.

@maxsokolov
Created November 3, 2016 08:51
Show Gist options
  • Save maxsokolov/c21037c3a6e7a3d963db235fe10d30c9 to your computer and use it in GitHub Desktop.
Save maxsokolov/c21037c3a6e7a3d963db235fe10d30c9 to your computer and use it in GitHub Desktop.
gcd based timer using swift
private let timerQueue = DispatchQueue(label: "com.timer.queue", attributes: [])
final class Timer : NSObject {
private var timer: DispatchSourceTimer?
var active: Bool {
return timer != nil
}
func start(_ interval: Int, repeats: Bool = false, handler: @escaping () -> Void) {
cancel()
let timer = DispatchSource.makeTimerSource(queue: timerQueue)
self.timer = timer
timer.scheduleRepeating(deadline: .now() + .seconds(interval), interval: .seconds(interval))
timer.setEventHandler {
if !repeats {
self.cancel()
}
DispatchQueue.main.async(execute: handler)
}
timer.resume()
}
func cancel() {
guard let timer = timer else { return }
timer.cancel()
self.timer = nil
}
deinit {
cancel()
}
}
@e-kazakov
Copy link

e-kazakov commented Jan 29, 2018

Line 20 - reference cycle.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment