2012-04-23 11 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