0

I am trying to give a time limit of 2 seconds and total trials of 3 for an async network call to execute and finish. and after the 2 seconds, the call should try one more time then exists with a failure.

I tried this. but its not exiting with an error after the two seconds. which makes sense since I am checking for deadline before firing the async call. but not sure how else to approach it.

func getDetails() async {
    // maximum amounts of trials
    let maxRetryCount = 2
    let deadlineInSec = 1

    for _ in 0..<maxRetryCount {
        guard !self.isSuccess else {
            break
        }
        do {
            // setting deadline for 2 secs
            if let deadline = Calendar.current.date(byAdding: .second,
                                                    value: deadlineInSec,
                                                    to: Date()),
               Date() >= deadline {
                throw TaskRetryingError.timedOut
            }
            let response = try await networkCall()
            await MainActor.run {
                self.data = data
                self.isSuccess = true
            }
        } catch {
            // If any error occurs, other than
            if error as? TaskRetryingError != TaskRetryingError.exceededMaxRetryCount{
                continue
            }
            // handling error.
        }
    }
}
burnsi
  • 6,194
  • 13
  • 17
  • 27
AbEls
  • 1
  • 1
    One approach is to have two tasks, one for the network request, another with the timeout, which will cancel the task associated with the network request after a period of time. Perhaps like https://stackoverflow.com/q/74710155/1271826. Or perhaps keep it simpler and just set the timeout in the `URLRequest` or `URLSession` (e.g. [`timeoutIntervalForResource`](https://developer.apple.com/documentation/foundation/urlsessionconfiguration/1408153-timeoutintervalforresource)). – Rob Feb 03 '23 at 07:36
  • This begs the question as to why you wouldn’t want to let a network request finish. E.g., let’s say you have a timeout of 1 second and the server is under so much load that it consistently takes 2 seconds. Does it really help the situation to have all the client devices sending multiple computationally intense requests, each timing out, and sending new requests? That is going to end up taxing your server a lot more than just letting it finish. And the more devices doing this, the worse it is on the server. And repeatedly giving up and retrying will actually be slower on device, too. – Rob Feb 03 '23 at 07:44

0 Answers0