I am trying to execute a certain block of code every x amount of time, but it seems that all I am doing is executing it during that time. Here's a block of my code.
我正在尝试每x次执行一个特定的代码块,但是看起来我所做的就是在这段时间内执行它。这是我的代码块。
while (TRUE) {
NSTimer *countDown = [NSTimer
scheduledTimerWithTimeInterval:(x)
target:self
selector:@selector(timerHandle)
userInfo:nil
repeats:YES];
}
Any ideas as to how to do it?
有什么办法吗?
2 个解决方案
#1
4
As written, this is an infinite loop, creating an NSTimer
every loop iteration.
如前所述,这是一个无限循环,每次循环都创建一个NSTimer。
Try it without the while
loop. This should cause [self timerHandle]
to be invoked on interval x
by a single background thread/timer. The Apple guide to NSTimer usage (including as others point out, how to properly stop your timed task) is here.
尝试它没有while循环。这应该会导致(self timerHandle)在interval x上被单个后台线程/计时器调用。NSTimer使用的苹果指南(包括其他人指出的,如何正确地停止计时任务)在这里。
#2
4
Try this: (It will call executeMethod
on every 5 sec)
试试这个:(它会每5秒调用一个executeMethod)
if (![NSThread isMainThread]) {
dispatch_async(dispatch_get_main_queue(), ^{
[NSTimer scheduledTimerWithTimeInterval:5.0
target:self
selector:@selector(executeMethod)
userInfo:nil
repeats:YES];
});
}
else{
[NSTimer scheduledTimerWithTimeInterval:5.0
target:self
selector:@selector(executeMethod)
userInfo:nil
repeats:YES];
}
Write the code you want to be executed in executeMethod
method. Hope this helps.. :)
编写希望在executeMethod方法中执行的代码。希望这可以帮助. .:)
#1
4
As written, this is an infinite loop, creating an NSTimer
every loop iteration.
如前所述,这是一个无限循环,每次循环都创建一个NSTimer。
Try it without the while
loop. This should cause [self timerHandle]
to be invoked on interval x
by a single background thread/timer. The Apple guide to NSTimer usage (including as others point out, how to properly stop your timed task) is here.
尝试它没有while循环。这应该会导致(self timerHandle)在interval x上被单个后台线程/计时器调用。NSTimer使用的苹果指南(包括其他人指出的,如何正确地停止计时任务)在这里。
#2
4
Try this: (It will call executeMethod
on every 5 sec)
试试这个:(它会每5秒调用一个executeMethod)
if (![NSThread isMainThread]) {
dispatch_async(dispatch_get_main_queue(), ^{
[NSTimer scheduledTimerWithTimeInterval:5.0
target:self
selector:@selector(executeMethod)
userInfo:nil
repeats:YES];
});
}
else{
[NSTimer scheduledTimerWithTimeInterval:5.0
target:self
selector:@selector(executeMethod)
userInfo:nil
repeats:YES];
}
Write the code you want to be executed in executeMethod
method. Hope this helps.. :)
编写希望在executeMethod方法中执行的代码。希望这可以帮助. .:)