Created
October 26, 2015 08:52
-
-
Save kakajika/a71480e71d18151db9d8 to your computer and use it in GitHub Desktop.
Cancellable delayed task in 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
class CancellableDelayedTask { | |
var cancelled = false | |
func run(delay: Double, task: () -> Void ) { | |
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) | |
dispatch_after(time, dispatch_get_main_queue()) { [unowned self] () -> Void in | |
if !self.cancelled { | |
task() | |
} | |
} | |
} | |
func cancel() { | |
cancelled = true | |
} | |
} |
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
let task = CancellableDelayedTask() | |
task.run(3.0 * Double(NSEC_PER_SEC)) { () -> Void in | |
// Do something... | |
} | |
task.cancel() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment