Delay timer after first fire

前端 未结 2 1670
甜味超标
甜味超标 2021-01-07 01:51

I have a timer in my application that triggers a certain event:

myTimer =  NSTimer.scheduledTimerWithTimeInterval(10, target: self,
    selector: \"searchFor         


        
相关标签:
2条回答
  • 2021-01-07 02:03

    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.

    0 讨论(0)
  • 2021-01-07 02:07

    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.

    0 讨论(0)
提交回复
热议问题