Delay timer after first fire

2020-03-07 06:22发布

问题:

I have a timer in my application that triggers a certain event with the following method

myTimer =  NSTimer.scheduledTimerWithTimeInterval(10, target: self,
    selector: "searchForDrivers:", userInfo:nil, repeats: true)

I notice it triggers with the delay of 10 ms for the first time. I don’t want to delay user for the first time. But for the second request I want it to be delayed with 10 ms. How can I acheive this?

回答1:

First schedule the timer as you've done.

timer =  NSTimer.scheduledTimerWithTimeInterval(
    10.0, target: self,
    selector: "searchForDrivers:",
    userInfo: nil,
    repeats: true
)

Then, immediately afterwards, fire timer.

timer.fire()

According to the documentation,

You can use this method to fire a repeating timer without interrupting its regular firing schedule. If the timer is non-repeating, it is automatically invalidated after firing, even if its scheduled fire date has not arrived.

See the NSTimer Class Reference for more information.



回答2:

One more way to do that is you can use two timers for that like:

var myTimer = NSTimer()
var secondTimer = NSTimer()

After that you can set two timers this way:

myTimer =  NSTimer.scheduledTimerWithTimeInterval(0, target: self,
    selector: "searchForTRuckDrivers", userInfo:nil, repeats: false)
secondTimer =  NSTimer.scheduledTimerWithTimeInterval(10, target: self,
    selector: "searchForTRuckDrivers", userInfo:nil, repeats: true)

You can set first timer with delay 0 which will not repeat again while set another timer with delay 10 and it will repeat again and again.

After that in method you can invalidate first timer this way:

func searchForTRuckDrivers() {        
    if myTimer.valid {
        myTimer.invalidate()
    }
}

This will remove first timer but second timer will call this method with delay.

Hope it will help.



标签: ios swift timer