Black Friday 2024 deal: 30% off our Swift and SwiftUI books! Learn more ...Black Friday 2024 deal:30% off our Swift and SwiftUI books >>
Quick Tip Icon
Quick Tip

Delay an async Task in Swift using the new clock APIs

In Swift 5.7 we have new APIs for interacting with time, that consist of three main components: clock, instant and duration. We can use these new APIs to delay an async Task in a more descriptive way than with the old API that accepted nanoseconds.

In the following example, we use Instant.now property to get the current instant, and add a Duration of 10 seconds to delay the task by 10 seconds. We can also specify a duration for tolerance, which would allow the underlying scheduling mechanisms to slightly adjust the deadline if necessary for more power efficient execution. We can choose either continuous or suspending clock, depending on whether we would like it to continue incrementing while the system is asleep.

Task {
    print("starting the task")
    
    try await Task.sleep(
        until: .now + .seconds(10),
        tolerance: .seconds(2),
        clock: .suspending
    )
    
    print("continuing the task")
}

As someone who has worked extensively with Swift, I've gathered many such insights over the years. I'm excited to share these in my new book Swift Gems. This book is packed with advanced tips and techniques to help intermediate and advanced Swift developers enhance their coding skills. From optimizing collections and handling strings to mastering asynchronous programming and debugging, "Swift Gems" provides practical advice to elevate your Swift development. Grab your copy of Swift Gems and let's explore the advanced techniques together.

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Black Friday 2024 offer: 30% off!$35$25

100+ tips to take your Swift code to the next level

Swift Gemsby Natalia Panferova

  • Advanced Swift techniques for experienced developers bypassing basic tutorials
  • Curated, actionable tips ready for immediate integration into any Swift project
  • Strategies to improve code quality, structure, and performance across all platforms
Black Friday 2024 offer: 30% off!

100+ tips to take your Swift code to the next level

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Swift Gems

by Natalia Panferova

$35$25