Skip to content

Commit 8c9d19e

Browse files
committed
Add Clock.sleep(for:).
1 parent 71c62c0 commit 8c9d19e

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

stdlib/public/Concurrency/Clock.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,20 @@ extension Clock {
7676
return start.duration(to: end)
7777
}
7878
}
79+
extension Clock {
80+
/// Suspends for the given duration.
81+
///
82+
/// Prefer to use the `sleep(until:tolerance:)` method on `Clock` if you have access to an
83+
/// absolute instant.
84+
@available(SwiftStdlib 5.7, *)
85+
@_alwaysEmitIntoClient
86+
public func sleep(
87+
for duration: Instant.Duration,
88+
tolerance: Instant.Duration? = nil
89+
) async throws {
90+
try await self.sleep(until: self.now.advanced(by: duration), tolerance: tolerance)
91+
}
92+
}
7993

8094
enum _ClockID: Int32 {
8195
case continuous = 1

stdlib/public/Concurrency/TaskSleepDuration.swift

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ extension Task where Success == Never, Failure == Never {
139139
public static func sleep<C: Clock>(
140140
until deadline: C.Instant,
141141
tolerance: C.Instant.Duration? = nil,
142-
clock: C
142+
clock: C = ContinuousClock()
143143
) async throws {
144144
try await clock.sleep(until: deadline, tolerance: tolerance)
145145
}
@@ -156,8 +156,12 @@ extension Task where Success == Never, Failure == Never {
156156
/// - Parameter duration: The duration to wait.
157157
@available(SwiftStdlib 5.7, *)
158158
@_alwaysEmitIntoClient
159-
public static func sleep(for duration: Duration) async throws {
160-
try await sleep(until: .now + duration, clock: .continuous)
159+
public static func sleep<C: Clock>(
160+
for duration: C.Instant.Duration,
161+
tolerance: C.Instant.Duration? = nil,
162+
clock: C = ContinuousClock()
163+
) async throws {
164+
try await sleep(until: clock.now.advanced(by: duration), tolerance: tolerance, clock: clock)
161165
}
162166
}
163167
#else
@@ -169,13 +173,17 @@ extension Task where Success == Never, Failure == Never {
169173
public static func sleep<C: Clock>(
170174
until deadline: C.Instant,
171175
tolerance: C.Instant.Duration? = nil,
172-
clock: C
176+
clock: C = ContinuousClock()
173177
) async throws {
174178
fatalError("Unavailable in task-to-thread concurrency model")
175179
}
176180
@available(SwiftStdlib 5.7, *)
177181
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
178-
public static func sleep(for duration: Duration) async throws {
182+
public static func sleep<C: Clock>(
183+
for duration: C.Instant.Duration,
184+
tolerance: C.Instant.Duration? = nil,
185+
clock: C = ContinuousClock()
186+
) async throws {
179187
fatalError("Unavailable in task-to-thread concurrency model")
180188
}
181189
}

0 commit comments

Comments
 (0)