I'm trying to have a Task wait until a Foundation Date, but I can't quite figure out the necessary incantation:
// I don't know how to build a ContinuousClock.Instant from a Date
let instant: ContinuousClock.Instant = ???
try await Task.sleep(until: instant)
// I can't find the UTCClock mentioned in SE-0329
// <https://github.com/apple/swift-evolution/blob/main/proposals/0329-clock-instant-duration.md>
try await Task.sleep(until: date, using: ???)
I did try to Google for a solution, but I remain clueless
May I ask for your help, if you know a technique that achieves this goal?
let targetDate: Date = …
let seconds = targetDate.timeIntervalSinceNow
try await Task.sleep(for: .seconds(seconds))
Alternatively, you can first create an Instant with ContinuousClock.Instant.now + .seconds(seconds) and then use sleep(until:), but that seems unnecessary.
I do indeed have a target Date, but the current date (now) is injected, for testability and previews. I ended up with:
// Works for both past and future dates.
// For past dates, seconds is negative, and Task.sleep
// returns immediately.
let seconds = targetDate.timeIntervalSince(currentDate())
try await Task.sleep(for: .seconds(seconds))