NSTimer start and call method every 2 seconds and stop after 3 minutes

2.2k views Asked by At

i know how to start NSTimer and i given the code for this but now i want to stop the NSTimer after 3 or 4 minutes but how can i do this

i know how to give NSTimer but how to stop after 3 minutes need some help

NSTimer* myTimer;
    myTimer= [NSTimer scheduledTimerWithTimeInterval: 2.0 target: self
                                                      selector: @selector(updateUIinMainThread:) userInfo: nil repeats: YES];
3

There are 3 answers

2
Ashish Kakkad On BEST ANSWER

Declaration :

int totalSeconds;
NSTimer *twoMinTimer;

Code :

- (void)timer {
    totalSeconds--;

    if ( totalSeconds == 0 ) {
        [twoMinTimer invalidate];
        //Timer stops after 2 minute from this you can do your stuff here
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    totalSeconds = 120;
    twoMinTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                   target:self
                                                 selector:@selector(timer)
                                                 userInfo:nil
                                                  repeats:YES];
}

Hope this helps

0
Anuj On

May be the following code will help you:

step 1: declare following instance variables

@interface yourclass : NSObject {

NSTimer* myTimer;
NSDate *initialDate;

}

step 2: create myTimer in your class where you want:

    myTimer= [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(callByTimer) userInfo:nil repeats:YES];

step 3: implement callByTimer method:

- (void)callByTimer{
// get initial date at very first call by myTimer

if (!initialDate)
{
    initialDate = [NSDate date];
}

// get current date
NSDate *currentDate = [NSDate date];

// get seconds between currentdate and initial date
NSTimeInterval secondsBetween = [currentDate timeIntervalSinceDate:initialDate];

// convert seconds into minutes
NSInteger minutes = secondsBetween/60;

// check if minutes is greater than or equal to 3 then invalidate myTimer and assign nil to initialDate variable
if (minutes>=3)
{
    [myTimer invalidate];
    initialDate = nil;
}}
3
Fawad Masud On

Save the time when the timer is initiated

NSTimer* myTimer;
myTimer= [NSTimer scheduledTimerWithTimeInterval: 2.0 target: self
                                                  selector: @selector(updateUIinMainThread:) userInfo: nil repeats: YES];
savedTime = [NSDate date];

and in function updateUIinMainThread: compare current time to saved time. If the result is greater than 180 seconds, stop the timer.

-(void)updateUIinMainThread:(NSTimer *)timer
{
    NSDate *timeNow = [NSDate date];
    NSTimeInterval timespan = [timeNow timeIntervalSinceDate:savedTime];
    if(timesapn>180)
    {
       [timer invalidate];
    }
}