I want to call the method func adjustmentBestSongBpmHeartRate()
every 1.1 second. I used Timer, but it doesn't work. I have read the document and found a lot of sample code, it still does work! Is there anything I missed?
timer = Timer.scheduledTimer(timeInterval: 1.1, target: self, selector: #selector(self.adjustmentBestSongBpmHeartRate), userInfo: nil, repeats: false) timer.fire() func adjustmentBestSongBpmHeartRate() { print("frr") }
A Basic timer is declared as such: //declare blank timer variable var timer = Timer() //in a function or viewDidLoad() timer = Timer. scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true) //new function @objc func timerAction(){ print(“timer fired!”) }
selector() is where you'd add in the function that you want it to call every timeInterval you set. In your example it's every second. Do bare in mind that in Swift 4 and above, you need to add @objc before a function if you want to call it in a selector like so: @objc func handleEverySecond() { print("Hello world!")
I found that creating the timer in an OperationQueue Operation did not work. I assume this is because there is no runloop.
Therefore, the following code fixed my problem:
DispatchQueue.main.async { // timer needs a runloop? self.timeoutTimer = Timer.scheduledTimer(timeInterval: self.timeout, target: self, selector: #selector(self.onTimeout(_:)), userInfo: nil, repeats: false) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With