如何在一段时间后停止执行该方法? 我打电话的方法如下:
def make_decimal_to_n_ary_converter(n):
def converter(x):
if x==0 or x==1:
return x
i=x
b=('A','B','C','D','E','F')
result = ""
while i>0:
a=i%n #3
if a<10:
result = str(i%n)+result
else:
d=a-10
result = b[d] + result
i=i//n
return result
return converter
#Lines below are not to be changed, part of qn
decimal_to_binary = make_decimal_to_n_ary_converter(2)
decimal_to_octal = make_decimal_to_n_ary_converter(8)
decimal_to_hexadecimal = make_decimal_to_n_ary_converter(16)
这里我给出了5秒的间隔。因此,此方法将在每5秒后调用一次,因此一旦到达指定时间,我想停止此方法执行。
答案 0 :(得分:5)
取一个计数器变量,每次调用增加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];
}
}
答案 1 :(得分:2)
如果你想在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;
}
}
答案 2 :(得分:1)
你可以这样尝试
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];
}
}
答案 3 :(得分:1)
#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;
}
}
答案 4 :(得分:1)
试试这个;
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 :(得分:0)
尝试创建仅在一段时间后调用的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];
}