以随机时间间隔重复执行方法的最佳方法是什么,例如方法中的代码以 1s、3s、7s、10s、11s、13s、19s、22s 等运行。无限长的时间?
问问题
1412 次
4 回答
6
我会设置一个计时器,每次都通过检查随机数,如果该随机数命中,则调用该函数:
[NSTimer scheduledTimerWithInterval: 1.0 target:self selector:@selector(targetMethod:) userInfo:nil repeats: YES];
并在目标方法中
if(arc4random() % 10 == 1)
{
//call your function
}
于 2012-06-27T15:00:43.950 回答
2
int randomInt = (arc4random() % 100) + 1;
NSTimer *yourTimer = [NSTimer scheduledTimerWithTimeInterval:randomInt target:self selector:@selector(timedMethod:) userInfo:nil repeats:YES];
上面的代码将在 1s 到 100s 内以随机时间间隔触发
于 2012-06-27T14:59:41.687 回答
1
您可以根据需要或根据需要定义时间,计算并使用 -
[NSTimer scheduledTimerWithTimeInterval:yourTime target:self selector:@selector(mainloop) userInfo:nil repeats:YES];
于 2012-06-27T15:00:32.420 回答
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
于 2012-06-27T16:00:35.830 回答