Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to do polling in swift?

I have lot of experience with other programming languages, but not so much in swift 3. I want to do polling loop. This is what i have written:

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

This works fine for me, every 100 seconds, i do polling, and then make this thread sleep. What I am wondering, is this correct way to do this in swift 3?

like image 434
MegaManX Avatar asked Jun 05 '17 11:06

MegaManX


1 Answers

You have 2 options:

  • Use NSTimer
  • Use a DispatchSourceTimer

Using NSTimer is pretty easy, but it needs an active run loop, so if you need to poll on a background thread things could be a little bit tricky, because you will need to create a thread and keep alive a run loop on it (probably the timer itself will keep the run loop alive).
DispatchSourceTimer on the other hand works using queues. You can easily create a dispatch source timer from one of the system provided queues or create one.

    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()

The leeway arguments is the amount of time that the system can defer the timer.

like image 59
Andrea Avatar answered Sep 23 '22 03:09

Andrea