-
-
Save astrokin/48938e2be30b122a17b36f13bcbbd546 to your computer and use it in GitHub Desktop.
gcd based timer using swift
This file contains 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