FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

How to make a task sleep

Paul Hudson    @twostraws   

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 {
    static func sleep(seconds: Double) async throws {
        let duration = UInt64(seconds * 1_000_000_000)
        try await Task.sleep(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.

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for iOS devs who want to become complete senior developers — from October 18th to 24th. Learn how to apply iOS app architecture patterns through a series of lectures and practical coding sessions.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Buy Pro Swift 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 (Vapor Edition) 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 Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.