How to value for NSTimer

2019-06-10 10:02发布

问题:

I am making on application in which user have to select the time, example 5 min or 10 min or 15 min and after that the timer will run arround 15 seconds and will called another function.Timer should have to run after every 15 seconds, i have implemented the above the things and it is working, The only thing which i am not getting is that how to run NSTimer for 5 mins or 10 mins with 15 seconds timeframe, Like timer should run time interval for arround 15 seconds and after 5 minutes it should stop.

回答1:

You fire timer every 15 seconds and in the timer fire method, keep adding the time and when time reaches 10 mins (or 15 mins), stop the timer.

[NSTimer scheduledTimerWithTimeInterval:15.0f target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];

-(void) timerFireMethod:(NSTimer *) theTimer {
    _elapsedTime += 15.0f;
    if (_elapsedTime >= 5.0 * 60) {
        // elapsed time is 5 mins.
        [theTimer invalidate];
    }
}


回答2:

You can use 2 different NSTimers, one that fires every 15 secs, the second one that fires after 5 min and stops the first one. Could this work for you?



回答3:

you have to check nsdate one as global in appdelegate(static) or anywhere and one within function of timer which you call ..then set time interval for 15 seconds and check whether current minute has difference of 5 minutes from global timer if it matched then stop timer