我正在尝试使用 NSTimer 实现具有指数退避的重试逻辑。 我的代码如下所示:
-(void)start
{
[NSTimer scheduledTimerWithTimeInterval:0.0 target:self
selector:@selector(startWithTimer:) userInfo:nil repeats:NO];
}
-(void)startWithTimer:(NSTimer *)timer
{
if (!data.ready) {
// timer.timeInterval == 0.0 ALWAYS!
NSTimeInterval newInterval = timer.timeInterval >= 0.1 ? timer.timeInterval * 2 : 0.1;
newInterval = MIN(60.0, newInterval);
NSLog(@"Data provider not ready. Will try again in %f seconds.", newInterval);
NSTimer * startTimer = [NSTimer scheduledTimerWithTimeInterval:newInterval target:self
selector:@selector(startWithTimer:) userInfo:nil repeats:NO];
// startTimer.timeInteval == 0.0 ALWAYS!
return;
}
...
}
我遇到的问题是定时器 NSTimer scheduledTimerWithTimeInterval 似乎忽略了我提供的时间间隔并且总是将它设置为 0.0。关于我在这里做错了什么有什么建议吗?
最佳答案
Apple 文档中有关于 NSTimer
上的 timeInterval
属性的说明。
If the receiver is a non-repeating timer, returns 0 (even if a time interval was set).
您将需要使用一些其他方法来跟踪计时器间隔应该是多少。我在您的类里面推荐 iVar。
-(void)start
{
_timeInterval = 0.0;
[NSTimer scheduledTimerWithTimeInterval:_timeInterval target:self
selector:@selector(startWithTimer:) userInfo:nil repeats:NO];
}
-(void)startWithTimer:(NSTimer *)timer
{
if (!data.ready) {
_timeInterval = _timeInterval >= 0.1 ? _timeInterval * 2 : 0.1;
_timeInterval = MIN(60.0, _timeInterval);
NSLog(@"Data provider not ready. Will try again in %f seconds.", _timeInterval);
NSTimer * startTimer = [NSTimer scheduledTimerWithTimeInterval:_timeInterval target:self
selector:@selector(startWithTimer:) userInfo:nil repeats:NO];
return;
}
...
}
关于objective-c - 使用 NSTimer 实现指数退避重试逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10274761/