【问题标题】:iOS Timer loop that executes a certain action every X minutesiOS 计时器循环,每 X 分钟执行一次特定操作
【发布时间】:2014-03-12 01:49:03
【问题描述】:

我试图每隔 x 时间执行一个特定的代码块,但似乎我所做的只是在那段时间内执行它。这是我的代码块。

while (TRUE) {
    NSTimer *countDown = [NSTimer
                       scheduledTimerWithTimeInterval:(x)
                       target:self
                       selector:@selector(timerHandle)
                       userInfo:nil
                       repeats:YES];

}

关于如何做的任何想法?

【问题讨论】:

    标签: ios iphone objective-c timer nstimer


    【解决方案1】:

    正如所写,这是一个无限循环,每次循环迭代都会创建一个NSTimer

    尝试不使用while 循环。这应该会导致[self timerHandle] 在间隔x 上被单个后台线程/计时器调用。 Apple 的 NSTimer 使用指南(包括其他人指出的如何正确停止您的定时任务)是here

    【讨论】:

    • 是的。您还需要一种方法来停止计时器。
    • 谢谢,我想它做到了。我会检查停止部分的指南。
    【解决方案2】:

    试试这个:(它会每 5 秒调用一次executeMethod

    if (![NSThread isMainThread]) {
    
        dispatch_async(dispatch_get_main_queue(), ^{
            [NSTimer scheduledTimerWithTimeInterval:5.0
                                             target:self
                                           selector:@selector(executeMethod)
                                           userInfo:nil
                                            repeats:YES];
        });
    }
    else{
        [NSTimer scheduledTimerWithTimeInterval:5.0
                                         target:self
                                       selector:@selector(executeMethod)
                                       userInfo:nil
                                        repeats:YES];
    }
    

    executeMethod方法中编写你想要执行的代码。希望这会有所帮助.. :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-20
      • 1970-01-01
      • 1970-01-01
      • 2013-01-28
      • 1970-01-01
      • 2013-04-20
      相关资源
      最近更新 更多