Re: Observing Time
Re: Observing Time
- Subject: Re: Observing Time
- From: email@hidden
- Date: Fri, 26 Jul 2013 11:26:52 +0900
On Jul 26, 2013, at 11:08 AM, Rick Mann <email@hidden> wrote:
>
> On Jul 25, 2013, at 18:52 , email@hidden wrote:
>
>> I'm getting about a half second lag behind the system clock.
>> This is actually reasonable for my purposes, but I wonder if I'm missing something that might be more in sync.
>
> You can do this using NSTimers, but you need to make sure you adjust for the current fraction of a second. That is, if you simply set up a scheduled timer with a one-second interval, you'll get called every second, but it won't necessarily be at the instant the wall clock second ticks over.
>
> So, thing to do is to create a repeating timer with a fire date rounded to the next second and a one-second interval. Something like this (written off-the-cuff, so might need some tweaking):
>
> CFAbsoluteTime fireDateAbs = CFAbsoluteTimeGetCurrent();
> fireDateAbs = trunc(fireDateAbs + 0.5); // Round to the next second
> NSDate* fireDate = [NSDate dateWithTimeIntervalSinceReferenceDate: fireDateAbs];
> mTimer = [[NSTimer alloc] initWithFireDate: fireDate interval: 1.0 target: self selector: @selector(update:) userInfo: nil repeats: true];
> [[NSRunLoop currentRunLoop] addTimer: mTimer forMode: NSRunLoopCommonModes];
>
>
Yep, I know of these, but this is tied to the run loop and timers on the runloop can be delayed.
The reason I went with dispatch_timer is because it can be done with its own thread and if I understand correctly, frees it from the runloop...
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0UL));
dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0),
(unsigned)(delayInSeconds * NSEC_PER_SEC), 0);
dispatch_source_set_event_handler(_timer, ^{
// Get updated time here.
dispatch_async(dispatch_get_main_queue(), ^{
// Talk back to main thread here.
});
});
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden