Alex Stone
Alex Stone

Reputation: 47364

iPhone iOS how to initialize GCD dispatch timer with a specific fire time?

I'm looking to start the timer in the code below at a specific time and cannot find a way of instantiating dispatch_time_t with the time I want. I'm particularly not sure how to get mach_absolute_time to initialize the delay.

I saw some answers on how to initialize dispatch_time_t after a certain delay:

dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);

Which is not what I need.

Here's what I want to do:

This way I want my timer to start firing predictably at every second + 20 milliseconds and repeat at predictable times. How can I accomplish that?

Here's my current dispatch timer code

backgroundQueue = dispatch_queue_create("com.eeg.bgqueue", DISPATCH_QUEUE_SERIAL);

    synchronizeTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, backgroundQueue);
//I want to specify when the timer will fire
    dispatch_source_set_timer(synchronizeTimer, DISPATCH_TIME_NOW, NSEC_PER_MSEC * updateIntervalms/2.0, NSEC_PER_MSEC * 0);
    dispatch_source_set_event_handler(synchronizeTimer, ^
                                      {

                                             // do your processing here
                                           [activeConnection sendNetworkPacketThreadSafe:[circularArray objectAtIndex:lastArrayIndex]];



                                      });

Upvotes: 0

Views: 1105

Answers (1)

das
das

Reputation: 3681

It sounds like you want a wallclock-based timer and not a mach_absolute_time-based timer.

See the manpage for dispatch_walltime(3), that takes a struct timespec base time that you can configure with your requirements based on the result of gettimeofday(2).

Upvotes: 1

Related Questions