Wait in the background thread for a random time
I am currently using this to wait 5 seconds on a background thread before calling a function: DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + 5, execute: {
This works great, but I want to wait for a random duration every time. Doing something like this:
let randomTime = Int(arc4random_uniform(10))
DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + randomTime, execute: {
gives me an error: Type of expression is ambiguous without more context
Greetings.
source to share
Try to enter the code:
let randomTime = Int(arc4random_uniform(10))
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(randomTime)) {
print("Delay is \(randomTime) sec")
//Do something here
}
You can also use .microseconds(Int)
and .nanoseconds(Int)
depending on your requirements.
source to share
Looking at the docs for , there are two overloads Dispatch
for the operator +
that will work for you:
public func +(time: DispatchTime, interval: DispatchTimeInterval) -> DispatchTime
public func +(time: DispatchTime, seconds: Double) -> DispatchTime
I suggest using the second function and initializing Double
instead Int
as you are trying to do now:
let randomTime = Double(arc4random_uniform(10))
source to share