Objective C : NStimer - 如何在 n 小时后停止计时器

Objective C : NStimer- How to stop timer after n hours

我已经使用下面的调用启动了计时器,需要在 n 小时后停止它

self.timer = [NSTimer scheduledTimerWithTimeInterval:20 target:self selector:@selector(sendLocationUpdates) userInfo:nil repeats:YES];

我可以想到的解决方案是在计时器启动时获取当前时间并不断添加时间直到达到阈值。或者有没有更好的方法来停止计时器?

简单的解决方案

声明两个属性

@property NSInteger counter;
@property NSTimeInterval interval;

在启动计时器之前将计数器设置为 0

  self.counter = 0;
  self.interval = 20.0;
  self.timer = [NSTimer scheduledTimerWithTimeInterval:self.interval target:self selector:@selector(sendLocationUpdates) userInfo:nil repeats:YES];

sendLocationUpdates 方法中递增计数器

  - (void)sendLocationUpdates
  {
    counter++;
    if (counter == 4 * (3600 / self.interval)) {
      [self.timer invalidate];
      self.timer = nil;
    }
   // do other stuff
  }

在给定的 20 秒时间间隔内,计时器每小时触发 180 次。 在示例中,计时器在 4 小时后停止

在class中添加一个实例变量来存储定时器的开始时间:

YourClass.m:

@interface YourClass () {
    NSTimeInterval _startTime;
}

@end

创建定时器时记录当前时间:

self.timer = [NSTimer scheduledTimerWithTimeInterval:20 target:self selector:@selector(sendLocationUpdates) userInfo:nil repeats:YES];
_startTime = [NSDate timeIntervalSinceReferenceDate];

并在sendLocationUpdates方法中测试当前时间:

#define TIMER_LIFE_IN_SECONDS 3000.0

- (void)sendLocationUpdates
{
    // do thing

    NSTimeInterval now = [NSDate timeIntervalSinceReferenceDate];
    if (now - _startTime > TIMER_LIFE_IN_SECONDS) {
        [self.timer invalidate];
        self.timer = nil;
    }
}