Hi everyone, thanks for reading.
I have a few long-running services within my app. I'm looking for a sanity check that there isn't anything wrong with doing something like this to create these services:
final actor MyService {
private var serviceTask: Task<(), Error>?
func start() {
serviceTask = Task {
repeat {
do {
try await Task.sleep(nano: 1_000_000_000 * 30) // sleep for 30 seconds. This throws if task is cancelled
await makeANetworkRequest()
} catch {
break
}
} while !Task.isCancelled
}
}
func stop() {
serviceTask?.cancel()
}
}
The goal here is to do some async work with a 30 second gap between firing. This is all good and well in the world of Swift Concurrency, right? The Task will suspend while sleeping, which allows other code to execute on the same thread, allowing the thread to always make forward progress.
I've been going down some ill-informed rabbit holes and started converting these services to use Timer
s, but I think I'm realizing that the problems were elsewhere.