Skip to main content

How to make a task sleep

About 2 minSwiftArticle(s)bloghackingwithswift.comcrashcourseswiftxcodeappstore

How to make a task sleep 관련

Swift Concurrency by Example

Back to Home

How to make a task sleep | Swift Concurrency by Example

How to make a task sleep

Updated for Xcode 15

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.

Tips

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

Similar solutions…
What’s the difference between a task and a detached task? | Swift Concurrency by Example

What’s the difference between a task and a detached task?
How to create and use task local values | Swift Concurrency by Example

How to create and use task local values
How to cancel a task group | Swift Concurrency by Example

How to cancel a task group
How to cancel a Task | Swift Concurrency by Example

How to cancel a Task
How to run tasks using SwiftUI’s task() modifier | Swift Concurrency by Example

How to run tasks using SwiftUI’s task() modifier

이찬희 (MarkiiimarK)
Never Stop Learning.