objective-c - 使用 NSTimer 实现指数退避重试逻辑

标签 objective-c ios foundation

我正在尝试使用 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 属性的说明。

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

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/

相关文章:

ios - 如何显示重叠 View iOS

iphone - AFJSONRequestOperation 响应延迟

objective-c - 如何获取pathsForResourcesOfType :inDirectory:?的目录参数

ios - 如何检查通用 swift 数组包含一个元素?

objective-c - 为什么 -isMemberOfClass : not work here?

objective-c - 如何识别导航堆栈中的前一个 View Controller

ios - 将pjsip集成到iOS应用中

ios - 如何使用 UIBarbuttonItem 切换播放和暂停

cocoa - 自终止 MacOS XPC 服务的正确方法是什么?

iphone - Foundation Framework 中我的 iPhone 上的应用程序列表