目前我有以下内容:
$counter = 0;
$actions_per_minute = 6;
$sleep_time = (int)(60 / $actions_per_minute);
do{
sleep($sleep_time);
$counter++;
} while($counter < $actions_per_minute);
使用此代码,脚本每 10秒就会休眠是否可以在 60秒上随机设置,而不是每隔 10秒< / strong>所以可能两次在第一个 10秒,睡眠7秒等等....
答案 0 :(得分:1)
生成一个N个随机数($ actions_per)的列表,它们加起来一定的值($ total_time):
$sleep_times = [];
$actions_per = 6;
$total_time = 60;
$sum = 0;
for ($action = 0; $action < $actions_per; $action++ ) {
$random_interval = rand(0,$total_time);
array_push($sleep_times, $random_interval);
$sum = $sum + $random_interval;
}
$scaleFactor = $sum / $total_time;
$checksum = 0;
foreach( $sleep_times as $sleep_time ){
$scaled = $sleep_time / $scaleFactor;
$checksum = $checksum + $scaled;
echo $scaled."\n";
}
echo "Check:".$checksum;
结果:
$ actions_per = 6,$ total_time = 60:
9.2523364485981
3.9252336448598
12.056074766355
16.822429906542
11.495327102804
6.4485981308411
Check:60
$ actions_per = 12,$ total_time = 60:
9.0532544378698
8.5207100591716
6.5680473372781
2.3076923076923
9.0532544378698
3.3727810650888
3.5502958579882
4.6153846153846
4.4378698224852
2.1301775147929
4.792899408284
1.5976331360947
Check:60
$ actions_per = 6,$ total_time = 120:
23.907156673114
18.568665377176
3.0174081237911
25.299806576402
23.675048355899
25.531914893617
Check:120
答案 1 :(得分:-1)
使用以下方法管理修复它:
//start
$number_of_groups = 6;
$sum_to = 60;
$groups = [];
$group = 0;
$counter = 0;
while(array_sum($groups) != $sum_to) {
$groups[$group] = mt_rand(1, $sum_to/mt_rand(1,5));
if(++$group == $number_of_groups) {
$group = 0;
}
}
do{
$sleep_time = array_pop($groups);
sleep($sleep_time);
$counter++;
echo date("Y-m-d H:i:s")." - we just slept for ".$sleep_time." & we have ".json_encode($groups)." left</br></hr>";
} while($counter < $number_of_groups);
die();
//end