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.

+3


source to share


3 answers


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.

+2


source


.now () returns the DispatchTime type. Something like

DispatchQueue.global(qos: .background).asyncAfter(deadline: DispatchTime(uptimeNanoseconds: [any_random_generator]......

      



should do. note that any_random_generator should return UInt64 and that time is expressed in nanoseconds

0


source


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))

      

0


source







All Articles