Richard Birkett
Richard Birkett

Reputation: 781

dispatch_after time triggers immediately

This is the first time I've used GCD, I'll admit, so sorry if I've been stupid. I have a dispatch_after command which acts as a handy delay for me.

My problem is that when I send

dispatch_after(500000000000, dispatch_get_main_queue()){
    println("triggered") //or any other code
}

the closure is triggered immediately (e.g. I have tested this and "triggered" prints immediately). It should take longer right? Like 500 seconds longer.

Thanks :)

Upvotes: 1

Views: 388

Answers (1)

Stuart
Stuart

Reputation: 37053

The first parameter of dispatch_after(_:_:_:) is not a delay, but a point in time. From the docs:

when: The temporal milestone returned by dispatch_time or dispatch_walltime.

Discussion This function waits until the specified time and then asynchronously adds block to the specified queue.

You need to construct a delay relative to the current time, using dispatch_time(_:_:):

let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(500 * NSEC_PER_SEC))
dispatch_after(delayTime, dispatch_get_main_queue()) { ... }

Upvotes: 9

Related Questions