NSTimer 每 2 秒启动并调用一次方法,并在 3 分钟后停止

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

我知道如何启动 NSTimer,并且我给出了相关代码,但现在我想在 3 或 4 分钟后停止 NSTimer,但我该怎么做

我知道如何给 NSTimer 但如何在 3 分钟后停止 需要一些帮助

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

保存定时器启动的时间

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

并在函数 updateUIinMainThread: 中将当前时间与保存的时间进行比较。如果结果大于 180 秒,则停止计时器。

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

声明:

int totalSeconds;
NSTimer *twoMinTimer;

代码:

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

希望对您有所帮助

以下代码可能会对您有所帮助:

第 1 步:声明以下实例变量

@interface 你的class:NSObject {

NSTimer* myTimer;
NSDate *initialDate;

}

第 2 步:在 class 中您想要的位置创建 myTimer:

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

第 3 步:实现 callByTimer 方法:

- (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;
}}