2012-04-23 51 views
5

我试图使用NSTimer实现指数退避的重试逻辑。 我的代码如下所示:使用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。任何建议我在做什么错在这里?

回答

5

Apple文档对NSTimer上的timeInterval属性有这个说法。

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nstimer_Class/Reference/NSTimer.html

如果接收机是一种非重复计时器,返回0(即使时间间隔设定)。

您需要使用一些其他方法来跟踪定时器间隔应该是什么。我建议你的班上有一个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; 
    } 

    ... 
} 
+0

谢谢!我想我应该在下次阅读文档。 :) – Ivan 2012-04-23 05:20:17