aaron.anderson
aaron.anderson

Reputation: 49

Timing triggers

I'm trying to create a control method that executes submethods in separate threads. I have looked into NSTimer, but a couple of the submethods are not being executed in an exact time interval.

Here are the 5 intervals:

  1. Executes rapidly -- ~ every 0.1 seconds
  2. Executes every 5 minutes
  3. Executes every 10 minutes
  4. Executes every hour on the hour
  5. Executes every day on the day (at midnight)

Interval 1 - 3 should be very easy to do with the NSTimer. Any tips for implementing the other ones?

Thanks in advance!

Upvotes: 1

Views: 161

Answers (1)

iluvcapra
iluvcapra

Reputation: 9464

For (4) and (5), you want dispatch_walltime, if NSTimer isn't being accurate enough.

/* timespec for midnight, new years day 2014 */

struct tm time = {
   .tm_sec = 0,
   .tm_min = 0,
   .tm_hour = 0,
   .tm_mday = 1,
   .tm_mon = 1,
   .tm_year = 2014,
   .tm_wday = -1,  // I think -1 is wildcard here, can someone help?
   .tm_yday = -1,
   .tm_isdst = TRUE
};

const struct timespec whenToFire = {
   .tv_sec = mktime(time),
   .tv_nsec = 0
};

dispatch_time_t time = dispatch_walltime(&whenToFire,0);

/* a lower-priority queue may delay firing */    
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT);

dispatch_source_t timeSrc = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 
                                  0, 0, queue);

dispatch_source_set_timer(timeSrc, time, 100000 , 100);

dispatch_source_set_event_handler(timeSrc, ^{   
    /* only run once */
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        /* code to run on New Years Day here */
        dispatch_source_cancel(timeSrc);
    });
});

Upvotes: 1

Related Questions