如何在一定时间后停止执行方法? 我如下调用方法:5分钟后停止方法执行
[NSTimer scheduledTimerWithTimeInterval:5.0f
target:self
selector:@selector(doSomeTask) userInfo:nil repeats:YES];
在这里,我已经给5秒钟的时间间隔。所以这个方法每5秒钟会被调用一次,所以一旦达到指定的时间我想停止这个方法的执行。
如何在一定时间后停止执行方法? 我如下调用方法:5分钟后停止方法执行
[NSTimer scheduledTimerWithTimeInterval:5.0f
target:self
selector:@selector(doSomeTask) userInfo:nil repeats:YES];
在这里,我已经给5秒钟的时间间隔。所以这个方法每5秒钟会被调用一次,所以一旦达到指定的时间我想停止这个方法的执行。
尝试创建NSTimer
,将一段时间只有一次之后调用:
NSTimer *previous [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(doSomeTask) userInfo:nil repeats:YES];
[NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(stopPrevious) userInfo:nil repeats:NO];
-(void)stopPrevious{
[previous invalidate];
}
你可以尝试这样的
NSTimer *reachTimer;
NSInteger secondsLeft;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
secondsLeft = 0;
reachTimer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];
}
-(void)updateCounter:(NSTimer *)theTimer{
secondsLeft = secondsLeft+5;
if(secondsLeft>=300) // 60sec * 5min= 300
{
[reachTimer invalidate];
}
}
如果你想5分钟后停止您的电话。然后执行这样
@interface YourClass() {
int count;
}
@end
- (void)viewDidLoad {
count = 5;
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0f
target:self
selector:@selector(doSomeTask) userInfo:nil repeats:YES];
}
-(void) doSomeTask
{
count = count + 5;
if (count==300)
{
[timer invalidate];
timer=nil;
}
}
由5拍摄计数器变量,并增加每个呼叫(如时间间隔为5秒)等
counter = counter+5;
-(void) doSomeTask {
if (counter<=60) { // 5 min = 300 300/5 = 60
// Write method body here
counter = counter+5
}
else {
[timer invalidate];
}
}
#define TIMER_LIFE_IN_SECONDS 300.0
@interface YourClass() {
NSTimeInterval _startTime;
}
self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(doSomeTask) userInfo:nil repeats:YES];
_startTime = [NSDate timeIntervalSinceReferenceDate];
- (void) doSomeTask
{
// do thing
NSTimeInterval now = [NSDate timeIntervalSinceReferenceDate];
if (now - _startTime > TIMER_LIFE_IN_SECONDS) {
[self.timer invalidate];
self.timer = nil;
}
}
@uzair dhada检查此代码 – iOS
尝试此;
int count;
NSTimer *timer;
-(void)startTimertillLimit:(int)limit {
count = 0;
timer = [NSTimer scheduledTimerWithTimeInterval:5
target:self
selector:@selector(doSomething:)
userInfo:[NSString stringWithFormat:@"%d",limit]
repeats:YES];
}
-(void)doSomething:(NSTimer*)sender
{
int limit = (int)[sender.userInfo intValue];
count = count + 5;
if (count > limit)
{
[timer invalidate];
timer=nil;
count = 0;
}
}
感谢您的支持。 5分钟后我想停止doSomeTask方法。 –
@uzairdhada此方法将在5分钟后调用 –
好的,让我试试。 :) –