以随机时间间隔重复执行方法的最佳方法是什么,例如,方法中的代码在1s,3s,7s,10s,11s,13s,19s,22s等运行。无限的时间?
答案 0 :(得分:5)
我会设置一个计时器,每次通过检查一个随机数,如果该随机数命中,则调用该函数:
[NSTimer scheduledTimerWithInterval: 1.0 target:self selector:@selector(targetMethod:) userInfo:nil repeats: YES];
和targetMethod
if(arc4random() % 10 == 1)
{
//call your function
}
答案 1 :(得分:2)
int randomInt = (arc4random() % 100) + 1;
NSTimer *yourTimer = [NSTimer scheduledTimerWithTimeInterval:randomInt target:self selector:@selector(timedMethod:) userInfo:nil repeats:YES];
上面的代码将以1s到100s之间的随机时间间隔触发
答案 2 :(得分:1)
您可以根据需要或根据需要定义时间,计算并使用 -
[NSTimer scheduledTimerWithTimeInterval:yourTime target:self selector:@selector(mainloop) userInfo:nil repeats:YES];
答案 3 :(得分:1)
试试这个:
-(void) executeMethod
{
NSLog(@"Method being executed");
}
-(void) callingRandomTimedMethod
{
for (int i = 1; i > 0; i=i+2) {
[self executeMethod];
sleep(i);
}
}
这给出了输出(检查时间间隔):
> 2012-06-27 11:59:31.757 FirstApp[804:fb03] Method being executed
> 2012-06-27 11:59:32.760 FirstApp[804:fb03] Method being executed
> 2012-06-27 11:59:35.762 FirstApp[804:fb03] Method being executed
> 2012-06-27 11:59:40.765 FirstApp[804:fb03] Method being executed
> 2012-06-27 11:59:47.767 FirstApp[804:fb03] Method being executed
> 2012-06-27 11:59:56.769 FirstApp[804:fb03] Method being executed