2017-06-05 73 views
2

我對其他編程語言有很多經驗,但在swift中沒有那麼多3.我想做輪詢循環。這就是我寫:正確的方法來做swift投票?

DispatchQueue.global(qos: .userInitiated).async { 
      [unowned self] in 
      while self.isRunning { 
       WebService.getPeople(completion: nil) 
       sleep(100) 
      } 
     } 

這對我工作得很好,每100秒,我做的投票,然後讓這個線程睡眠。我想知道的是,這種在快速3中做到這一點的正確方法是什麼?

+1

首先,不要如果你可以。但是,如果你必須的話,只需使用一個'定時器' – Paulw11

+1

作爲一般規則,如果你可以避免長時間阻塞在調度線程上。 – JeremyP

+0

@JeremyP我聽到別人說完全一樣的東西,但我不明白爲什麼?如果我在一些低優先級的後臺線程上調度,會導致什麼問題? – MegaManX

回答

3

你有2種選擇:

  • 使用NSTimer
  • 使用DispatchSourceTimer

使用NSTimer是很容易的,但它需要一個活躍的運行循環,所以如果你需要輪詢一個後臺線程的事情可能有點棘手,因爲你需要創建一個線程並保持一個運行循環(可能定時器本身將保持運行循環活着)。
DispatchSourceTimer另一方面使用queues工作。您可以輕鬆地從一個系統提供的隊列中創建一個調度源定時器或創建一個。

var timer: DispatchSourceTimer? 
    let queue = DispatchQueue.global(qos: .background) 
    guard let timer = DispatchSource.makeTimerSource(queue: queue) else { return } 
    timer.scheduleRepeating(deadline: .now(), interval: .seconds(100), leeway: .seconds(1)) 
    timer.setEventHandler(handler: { 
     // Your code 
    }) 
    timer.resume() 

leeway參數是時間,該系統可以延遲計時器的量。