2017-08-08 118 views
1

我遵循this答案給出的建議。還是我的計時器是有時nil定時器正在發射兩次,並沒有n

func recreateTimer(){ 

     let timerLog = OSLog(subsystem: "LocationLogger", category: "Timer") 

     guard shouldUseTimer == true else { 
      os_log("we are using CoreMotion, no need to set timer", log: timerLog, type: .error) 
      return 
     } 
     if dwellingTimer != nil{ 

      dwellingTimer?.invalidate() 
      dwellingTimer = nil 
     } 

     lastDwelling = lastLocation 

     os_log("Moved more than 160 | invalidated previous timer began new timer", log: timerLog, type: .error) 

     DispatchQueue.main.async { [weak self] in 

      guard self?.dwellingTimer == nil else{ 
       os_log("Timer was not niled!!!", log: timerLog, type: .error) 
       return 
      } 
      self?.dwellingTimer = Timer.scheduledTimer(withTimeInterval: 60, repeats: false, block: { timer in 
       os_log("we reached 1 minute of no movement",log: timerLog, type: .fault) 
       self?.locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers 
       self?.beginMotionTracking() 
       os_log("Timer is deallocated & invalidated | Accuracy: %{public}f | RemainingTime: %{public}f",log: timerLog, type: .fault,(self?.locationManager.desiredAccuracy)!, UIApplication.shared.remainingTime()) 
      }) 
     } 
     os_log("New Timer is 'likely' set now", log: timerLog, type: .error) 
    } 

有時候我擊中

os_log("we are using CoreMotion, no need to set timer", log: timerLog, type: .error). 
+0

是否有可能在dispatchq塊中產生計時器是問題? – solenoid

+1

你應該在串行調度隊列中同步調度所有更新到你的'dwellingTimer'屬性,以確保操作是線程安全的 – Paulw11

+0

@ Paulw11我一定會這麼做的。我想我需要做的是創建一個串行隊列,並將計時器添加到主runloop或者只是將無效和'nil'ling放入'DispatchQueue.main.async'內......但是我不明白這是怎麼可能從一開始就是一個問題......主線程是一個串行隊列,並且還有'if dwellingTimer!= nil {...}也被串行調用。所以每個部分都應該沒問題... – Honey

回答

0

由於電磁閥和Paulw11意見,我瞭解到,相關的計時器所有執行應該做一種連續的方式。

另見invalidate

您必須從該定時器是 安裝線程發送此消息。如果您從另一個線程發送此消息,則與定時器關聯的輸入源 可能不會從其運行循環 中刪除,這可能會阻止該線程正常退出。

所以除了invalidatingnilling(你不想給非nil的對象不再傳達任何意義),請確保您:

  1. 使用相同的線程
  2. 您正在使用的線程是串行的
  3. 取決於您對定時器進行更改的位置,您可能需要也可能不需要同步。