Created
November 3, 2016 08:51
-
-
Save maxsokolov/c21037c3a6e7a3d963db235fe10d30c9 to your computer and use it in GitHub Desktop.
gcd based timer using swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 20 - reference cycle.