-
self.heartbeatTask = Task {
while true {
try await self.clock.sleep(for: .seconds(90))
self.doImportantThing()
}
} But I'm struggling to understand when this might throw, and if I need to worry about it. For context, I want this repeated chunk of work to ALWAYS happen, it's "safety critical" in the sense that it's for a parental controls app, and there is important work I want to do periodically to keep my contract with the parents, so I don't want some unexpected error case I hadn't thought of to tear down the task without my knowledge. But I was having trouble finding docs here or in Apple's frameworks about why and when this might throw. I thought from some things I read that it might be the case that it only throws if I cancel the task? Is that correct? If I never cancel this task, can I be confident that it will always keep looping? (I'm using a suspending variant, in case that helps). Or do I need to wrap it with a If there's any documentation of the conditions for throwing that someone could point me to, I'd be obliged. Thanks for the wonderful library! 🙏 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hi @jaredh159, I don't think it's documented, but you can look through the source code of I don't see any reason for you to force unwrap though. You can never be sure that you will never cancel the async context, and so it is better to not crash if that does happen. You can simply ignore it if you want with a Additionally, I would recommend using the |
Beta Was this translation helpful? Give feedback.
Hi @jaredh159, I don't think it's documented, but you can look through the source code of
ContinuousClock
and other clocks to see that the only error ever thrown isCancellationError
. And so it only throws if the surrounding async context is cancelled, such as yourheartbeatTask
. This would have been a very good use of typed throws to show thatsleep
only throws one kind of error.I don't see any reason for you to force unwrap though. You can never be sure that you will never cancel the async context, and so it is better to not crash if that does happen. You can simply ignore it if you want with a
do
/catch
, or you can let yourTask
be a throwing task.Additionally, I would recommend using…