Thomas
Thomas

Reputation: 315

Objective-C dispatch_after sometimes executes earlier than specified

I have some Objective-C code that I need to trigger after a specified time. I have been using the code below, and 95% of the time, it works great. However, sometimes the code will execute really early. Like 5 seconds instead of 60 seconds. It is completely inconsistent and I can't make it happen on purpose. Any idea what could cause this?

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(60 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    //do code stuff here
});

Upvotes: 1

Views: 437

Answers (1)

Rishil Patel
Rishil Patel

Reputation: 1995

I had same problem and my solution is:

dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC);
dispatch_after(delayTime, dispatch_get_main_queue(), ^(void){
    // YOUR CODE HERE
});

Hope this will work for you as well.

Upvotes: 2

Related Questions