Skip to content

Instantly share code, notes, and snippets.

@mdflores
Last active April 2, 2018 12:08
Show Gist options
  • Save mdflores/c1338e5b8a6086b3402aea2e516e7432 to your computer and use it in GitHub Desktop.
Save mdflores/c1338e5b8a6086b3402aea2e516e7432 to your computer and use it in GitHub Desktop.
RevokableTask adds a task delayed to the main queue which can be revoked or cancelled.
typealias TaskHandler = () -> ()
class RevokableTask {
private(set) var isCancelled: Bool = false
private(set) var task: TaskHandler
private(set) var delayTime: DispatchTime
private(set) var identifier: String
init(delayInSeconds: Double, task: @escaping TaskHandler) {
self.task = task
self.delayTime = .now() + delayInSeconds
self.identifier = UUID().uuidString
}
func execute() {
DispatchQueue.main.asyncAfter(deadline: self.delayTime) {
if !self.isCancelled {
self.task()
}
}
}
func revoke() {
self.isCancelled = true
}
}
let task = RevokableTask(delayInSeconds: 120) {
print("This task must not be executed...")
}
let task2 = RevokableTask(delayInSeconds: 120) {
print("Task is executing...")
}
task.execute()
task2.execute()
task.revoke()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment