How to trigger NSTimer right away?

二次信任 提交于 2019-12-04 14:58:00

问题


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 ?


回答1:


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

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




回答2:


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.




回答3:


In Swift:

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



回答4:


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];


来源:https://stackoverflow.com/questions/10764168/how-to-trigger-nstimer-right-away

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!