Home Delaying Work with DispatchQueue
Post
Cancel

Delaying Work with DispatchQueue

In mobile engineering, there are situations where we might need to introduce delays in our code execution. This delay could be useful for scenarios such as scheduling tasks, managing animations, or simulating real-world scenarios. In Swift, the DispatchQueue class, part of the Foundation framework, provides a powerful and efficient way to achieve this.

Here is a Delay class that encapsulates the functionality to delay the execution of tasks by a specified number of seconds. It offers methods to both schedule and cancel the execution of tasks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import Foundation

class Delay {
    
    private var seconds: Double
    var workItem: DispatchWorkItem?
    
    init(seconds: Double = 2.0) {
        self.seconds = seconds
    }
    
    func performWork(_ work: @escaping () -> Void) {
        workItem = DispatchWorkItem(block: {
            work()
        })
        DispatchQueue.main.asyncAfter(deadline: .now() + seconds, execute: workItem!)
    }
    
    func cancelWork() {
        workItem?.cancel()
    }
}

Usage

Using the Delay class is straightforward. Here’s a simple example demonstrating how to schedule and cancel a delayed task:

1
2
3
4
5
6
7
8
9
let delay = Delay(seconds: 3.0)

// Schedule a delayed task
delay.performWork {
    print("Delayed task executed!")
}

// Cancel the scheduled task before it executes
delay.cancelWork()
This post is licensed under CC BY 4.0 by the author.