Re: NSTimer fires ~0.0045 seconds early?
Re: NSTimer fires ~0.0045 seconds early?
- Subject: Re: NSTimer fires ~0.0045 seconds early?
- From: Brendan Younger <email@hidden>
- Date: Mon, 6 Aug 2001 02:28:33 -0500
On Sunday, August 5, 2001, at 11:22 PM, Brant Vasilieff wrote:
When I schedule my timer, It appears to sometimes fire early. So I
stored the desired date, and fetched the interval within timerFired:.
If it had been negative, than that would have implied that the timer
fired later than requested. What I ended up with surprised me. The
interval was not only positive, but further away from zero than I
thought. I ended up with numbers of 0.004 and 0.0045. Isn't
NSTimeInterval a double?
NSTimeInterval interval = [inDate timeIntervalSinceNow];
[NSTimer scheduledTimerWithTimeInterval:interval target:self
selector:@selector(timerFired:) userInfo:nil repeats:NO];
NSLog(@"new timer scheduled for %@.", [date
descriptionWithCalendarFormat:@"%I:%M:%S %p"]);
- (void)timerFired:(id)sender
{
NSTimeInterval interval = [date timeIntervalSinceNow];
NSLog(@"timer fired at %@.", [[NSCalendarDate calendarDate]
descriptionWithCalendarFormat:@"%I:%M:%S%p"]);
...
}
The output ends up like:
Aug 05 20:27:18 Test[6727] new timer scheduled for 08:28:00 PM.
Aug 05 20:27:59 Test[6727] timer fired at 08:27:59PM.
The problem, is that I reschedule the timer until the desired date is
reached. The last one almost always ends up getting called twice.
I guess I could add 0.01 seconds to the interval before I pass it in,
but I was surprised by the significance of the error. 0.004 seems
rather high to loose in what appears to be simply adding two double
numbers;
Brant
I believe much of this is touched upon in the NSTimer docs. NSTimer does
not have perfect resolution since it adds itself to the current run loop
and the run loop is then responsible for calling the method. Thus I
believe that the NSTimer cheats a bit and sends the message early so
that it is sure to arrive in time. My suggestion is to test for some
interval of granularity when you schedule the timer so as to avoid this
problem.
Brendan Younger