如何在一定時間後停止執行方法? 我如下調用方法: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分鐘後調用 –
好的,讓我試試。 :) –