ios - NSTimer 每 30 秒运行一次,但总是在 xx :00sec or xx:30sec of a minute 上触发

标签 ios swift nstimer

我有一个类似的问题:NSTimer run every minute but on first second

我希望计时器在下一分钟或下半分钟开始计时。假设当前时间是:12min:34sec 下一个所需的触发时间将是 13min:00sec ,如果是 12min:15sec 它应该开火 12min:30sec

基本上我需要在每分钟的 xx:00secxx:30sec 触发。

这是第一秒触发的代码:我需要为分秒找到正确的组件

    let currentCalendar = NSCalendar.currentCalendar()
    let unitFlags: NSCalendarUnit = [.Era, .Year, .Month, .Day, .Hour, .Minute]
    let components = currentCalendar.components(unitFlags , fromDate: NSDate())
    components.minute += 1
    components.second = 0

    let nextMinuteDate = currentCalendar.dateFromComponents(components)

    let reloadTimer = NSTimer.scheduledTimerWithTimeInterval(kReloadDataTimeInterval, target: self, selector: #selector(loadData) , userInfo: nil, repeats: false)
    reloadTimer.fireDate = nextMinuteDate!

最佳答案

  • 创建一个 NSTimer 属性

    var timer : NSTimer!
    
  • 使用非重复计时器和计算的时间间隔 (30 - (seconds-of-current-date % 30)) 在方法中初始化属性

    let currentSeconds = NSCalendar.currentCalendar().component(.Second, fromDate: NSDate())
    let initialInterval = NSTimeInterval(30 - currentSeconds % 30)
    timer = NSTimer.scheduledTimerWithTimeInterval(initialInterval, 
                                            target: self, 
                                          selector: #selector(firstTimerFired(_:)), 
                                          userInfo: nil, 
                                           repeats: false)
    
  • 在表示 选择器 的方法中,重新初始化定时器以 30 秒的间隔和第二个选择器重复。

    func firstTimerFired(aTimer : NSTimer) {
       NSLog("firstTimerFired")
       timer = NSTimer.scheduledTimerWithTimeInterval(30.0, 
                                               target: self, 
                                             selector: #selector(timerFired(_:)), 
                                             userInfo: nil, 
                                              repeats: true)
    }
    
  • 使用两个单独的选择器可以避免不必要的 if 子句来检查第一次运行

    func timerFired(aTimer : NSTimer) {
      NSLog("timerFired")
    }
    

NSLog 语句(而不是 print)还打印当前日期和时间以证明日期。

关于ios - NSTimer 每 30 秒运行一次,但总是在 xx :00sec or xx:30sec of a minute 上触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38589120/

相关文章:

ios - UITableView 在 ScrollView 时停止更新内容?

ios - PhoneGap 是否仅适用于 NativeApplications 或远程 Web 应用程序 HTML 页面?

ios - 如何让我的应用程序在 Twitter 上列入白名单以获取用户电子邮件?

javascript - iOS上的javascriptcore框架可以访问网络吗?

swift - 如何在 Swift 5 中正确使用子类

ios - 如何从 UnsafeMutablePointer<T> 构建 Data/NSData

iphone - 如何在不使用 ios 应用程序内购买的情况下处理付款?

ios - 为什么 iPhone 7 和 iPhone 7 Plus 屏幕截图会发送与 RGB 色彩空间图像不兼容的 alpha?

ios - Swift 选择器 - 发送到实例的无法识别的选择器

ios - NSTimer 没有正确传递参数?