简体   繁体   中英

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:

  • Get current time in milliseconds.
  • Get rid of the milliseconds part.
  • Add one second
  • Add 20 milliseconds.
  • create dispatch_time_t with that time
  • Pass it to the timer

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]];



                                      });

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM