Re: Observing Time
Re: Observing Time
- Subject: Re: Observing Time
- From: Ken Thomases <email@hidden>
- Date: Thu, 25 Jul 2013 22:09:10 -0500
On Jul 25, 2013, at 9:26 PM, email@hidden wrote:
> 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.
> });
> });
Since you're updating the GUI, you're tied to the responsiveness of the main thread's run loop, anyway. The dispatch to the main queue in the code above is conceptually similar to having a timer fire on the main thread's run loop.
Also, the above code doesn't adjust the timer to fire on the second as Rick suggested. You're asking it to fire every so many seconds (delayInSeconds) but you aren't specifying when during the second to fire. Rather than passing 0 as the second parameter of dispatch_walltime(), you should compute an adjustment to try to get close to a whole second. Since dispatch_walltime() uses gettimeofday() when you pass NULL for the first parameter, I'd use that same call to fill in a timeval structure and then pass NSEC_PER_SEC - (tp.tv_usec * NSEC_PER_USEC) as the second parameter.
Regards,
Ken
_______________________________________________
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