Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger NSTimer right away?

Tags:

ios

nstimer

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 ?

like image 855
Luc Avatar asked May 26 '12 06:05

Luc


2 Answers

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

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

like image 53
MCKapur Avatar answered Oct 12 '22 08:10

MCKapur


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.

like image 40
Jeff Avatar answered Oct 12 '22 10:10

Jeff