2017-06-05 53 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参数是时间,该系统可以延迟计时器的量。