How to trigger NSTimer right away?

IosNstimer

Ios Problem Overview


I need to call a method when my app starts and then call the same method every 5 seconds.

My code is pretty simple:

// Call the method right away
[self updatestuff:nil]

// Set up a timer  so the method is called every 5 seconds
timer = [NSTimer scheduledTimerWithTimeInterval: 5
                                          target: self
                                        selector: @selector(updatestuff:)      
                                        userInfo: nil
                                         repeats: YES];

Is there an option for the timer so it's trigger right away and then every 5 seconds ?

Ios Solutions


Solution 1 - Ios

NSTimer's -fire, [timer fire]; is what you're looking for.

That will fire/immediately call the timer dismissing the time delay.

Solution 2 - Ios

You can't schedule the timer and fire the event immediately all in the same line of code. So you have to do it in 2 lines of code.

First, schedule the timer, then immediately call 'fire' on your timer:

timer = [NSTimer scheduledTimerWithTimeInterval: 5
                                      target: self
                                    selector: @selector(updatestuff:)      
                                    userInfo: nil
                                     repeats: YES];
[timer fire];

When fire is called, the time interval that your timer waits to fire will reset because it just ran, and then will continue to run thereafter at the designated interval--in this case, every 5 seconds.

Solution 3 - Ios

In Swift:

timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(foo), userInfo: nil, repeats: true)
timer.fire()

Solution 4 - Ios

You can initialise the timer and fire it in the same line:

[(checkStatusTimer = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(checkStatusTimerTick:) userInfo:nil repeats:YES]) fire];

Solution 5 - Ios

In swift this can be achieved in one line like:

Timer.scheduledTimer(withTimeInterval: intervalInSec, repeats: true) { 

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLucView Question on Stackoverflow
Solution 1 - IosMCKapurView Answer on Stackoverflow
Solution 2 - IosJeffView Answer on Stackoverflow
Solution 3 - Iosinigo333View Answer on Stackoverflow
Solution 4 - IoshasanView Answer on Stackoverflow
Solution 5 - IosGlavidView Answer on Stackoverflow