Skip to content

Instantly share code, notes, and snippets.

@haldun
Created November 2, 2015 21:40
Show Gist options
  • Save haldun/e9c32c6c74ff5303869a to your computer and use it in GitHub Desktop.
Save haldun/e9c32c6c74ff5303869a to your computer and use it in GitHub Desktop.
class CancelableTimer: NSObject {
private var queue = dispatch_queue_create("timer", nil)
private var timer: dispatch_source_t!
private var firstTime = true
private var once: Bool
private var handler: () -> ()
init(once: Bool, handler: () -> ()) {
self.once = once
self.handler = handler
super.init()
}
func startWithInterval(interval: Double) {
firstTime = true
cancel()
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue)
dispatch_source_set_timer(timer, dispatch_walltime(nil, 0), UInt64(interval * Double(NSEC_PER_SEC)),
UInt64(0.05 * Double(NSEC_PER_SEC)))
dispatch_source_set_event_handler(timer) {
if self.firstTime {
self.firstTime = false
return
}
self.handler()
if self.once {
self.cancel()
}
}
dispatch_resume(timer)
}
func cancel() {
if timer != nil {
dispatch_source_cancel(timer)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment