WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

How to make a task sleep

Paul Hudson    @twostraws   

Updated for Xcode 14.2

Swift’s Task struct has a static sleep() method that will cause the current task to be suspended for at least some number of nanoseconds. Yes, nanoseconds: you need to write 1_000_000_000 to get 1 second. You need to call Task.sleep() using await as it will cause the task to be suspended, and you also need to use try because sleep() will throw an error if the task is cancelled.

For example, this will make the current task sleep for at least 3 seconds:

try await Task.sleep(nanoseconds: 3_000_000_000)

Important: Calling Task.sleep() will make the current task sleep for at least the amount of time you ask, not exactly the time you ask. There is a little drift involved because the system might be busy doing other work when the sleep ends, but you are at least guaranteed it won’t end before your time has elapsed.

Using nanoseconds is a bit clumsy, but Swift doesn’t have an alternative at this time – the plan seems to be to wait for a more thorough review of managing time in the language before committing to specific API.

In the meantime, we can add small Task extensions to make sleeping easier to accomplish. For example, this lets us sleep using seconds as a floating-point number:

extension Task where Success == Never, Failure == Never {
    static func sleep(seconds: Double) async throws {
        let duration = UInt64(seconds * 1_000_000_000)
        try await Task.sleep(nanoseconds: duration)

With that in place, you can now write Task.sleep(seconds: 0.5) or similar.

Calling Task.sleep() automatically checks for cancellation, meaning that if you cancel a sleeping task it will be woken and throw a CancellationError for you to catch.

Tip: Unlike making a thread sleep, Task.sleep() does not block the underlying thread, allowing it pick up work from elsewhere if needed.

Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Similar solutions…

Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.5/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.