Proper way to do polling in swift?

Viewed 7058

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?

3 Answers

Swift 5, iOS 10.0+

The code in the accepted answer no longer compiles, it can be modified (and simplified!) into:

DispatchQueue.global(qos: .userInitiated).async {
    let timer = Timer.scheduledTimer(withTimeInterval: 100, repeats: true) { timer in
        // Your action
    }
    timer.fire()
}

Swift 4 & Swift 5

 var timer: Timer? //declare outside function scope
 var runCount = 0


 self.timer = Timer(timeInterval: 2.0, target: self, selector: #selector(self.fireTimer), userInfo: nil, repeats: true)

 guard let timer = self.timer else {return}
 RunLoop.main.add(self.timer, forMode: RunLoop.Mode.default)

 @objc func fireTimer() {
         print("Timer fired! \(runCount)")
        runCount += 1

        if runCount == 5 {
            timer?.invalidate() //stop the timer
        }
    }

OR

self.timer = Timer.init(timeInterval: 1.0, repeats: true, block: { (timer) in
        print("\n--------------------TIMER FIRED--------------\n")
        runCount += 1
        if runCount == 5{
          timer.invalidate()
    }
    })
guard let timer = self.timer else {return}

RunLoop.main.add(self.timer!, forMode: RunLoopMode.defaultRunLoopMode)
Related