[英]How to generate random numbers at set time intervals?
I have developed code in Java for generating ten random numbers from a range 0 to 99. The problem is I need to generate a random number for every 2 min. 我已经用Java开发了代码,以生成从0到99范围的十个随机数。问题是我需要每2分钟生成一个随机数。 I am new to this area and need your views. 我是这个领域的新手,需要您的意见。
This example adds a random number to a blocking dequeue every two minutes. 本示例每两分钟将一个随机数添加到阻塞出队中。 You can take the numbers from the queue when you need them. 您可以在需要时从队列中提取数字。 You can use java.util.Timer as a lightweight facility to schedule the number generation or you can use java.util.concurrent.ScheduledExecutorService for a more versatile solution if you need more sophistication in the future. 您可以将java.util.Timer用作轻量级工具来安排数字生成,或者,如果将来需要更高级的功能,则可以使用java.util.concurrent.ScheduledExecutorService获得更通用的解决方案。 By writing the numbers to a dequeue, you have a unified interface of retrieving numbers from both facilities. 通过将数字写入出队,您将拥有一个统一的界面,可以从两个设施中检索数字。
First, we set up the blocking queue: 首先,我们设置阻塞队列:
final BlockingDequeue<Integer> queue = new LinkedBlockingDequeue<Integer>();
Here is the setup with java.utilTimer: 这是java.utilTimer的设置:
TimerTask task = new TimerTask() {
public void run() {
queue.put(Math.round(Math.random() * 99));
// or use whatever method you chose to generate the number...
}
};
Timer timer = new Timer(true)Timer();
timer.schedule(task, 0, 120000);
This is the setup with java.util.concurrent.ScheduledExecutorService 这是使用java.util.concurrent.ScheduledExecutorService进行的设置
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Runnable task = new Runnable() {
public void run() {
queue.put(Math.round(Math.random() * 99));
// or use whatever method you chose to generate the number...
}
};
scheduler.scheduleAtFixedRate(task, 0, 120, SECONDS);
Now, you can get a new random number from the queue every two minutes. 现在,您可以每两分钟从队列中获得一个新的随机数。 The queue will block until a new number becomes available... 队列将阻塞,直到有新的号码可用为止。
int numbers = 100;
for (int i = 0; i < numbers; i++) {
Inetger rand = queue.remove();
System.out.println("new random number: " + rand);
}
Once you are done, you can terminate the scheduler. 完成后,您可以终止调度程序。 If you used the Timer, just do 如果您使用计时器,则只需
timer.cancel();
If you used ScheduledExecutorService you can do 如果您使用ScheduledExecutorService,则可以执行
scheduler.shutdown();
You have two requirements which are unrelated: 您有两个不相关的要求:
To do anything every 2 minutes you can use a ScheduledExecutorService. 要每2分钟执行任何操作,可以使用ScheduledExecutorService。
You can schedule your program to be run once every two minutes using whatever scheduling features are available to you in your target environment (eg, cron
, at
, Windows Scheduled Tasks, etc.). 你可以安排你的程序运行一次使用每两分钟任何调度功能可供您在目标环境(例如, cron
, at
中,Windows计划任务等)。
Or you can use the Thread#sleep
method to suspend your application for 2,000ms and run your code in a loop: 或者,您可以使用Thread#sleep
方法将应用程序挂起2,000ms并在循环中运行代码:
while (loopCondition) {
/* ...generate random number... */
// Suspend execution for 2 minutes
Thread.currentThread().sleep(1000 * 60 * 2);
}
(That's just example code, you'll need to handle the InterruptedException and such.) (这只是示例代码,您需要处理InterruptedException等。)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.Timer;
public class TimerExample {
Random rand = new Random();
static int currRand;
TimerExample() {
currRand = rand.nextInt(99);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
currRand = rand.nextInt(99);
}
};
Timer timer = new Timer(2000, actionListener);
timer.start();
}
public static void main(String args[]) throws InterruptedException {
TimerExample te = new TimerExample();
while( true ) {
Thread.currentThread().sleep(500);
System.out.println("current value:" + currRand );
}
}
}
EDIT: Of course you should set 2000 in new Timer(2000, actionListener); 编辑:当然,您应该在新的Timer(2000,actionListener)中设置2000。 to 120 000 for two minutes. 到120 000持续两分钟。
I'm not entirely sure I understand the problem. 我不完全确定我了解这个问题。 If you wish to generate a different random number every two minutes, simply call your rnd
function every two minutes. 如果您希望每两分钟生成一个不同的随机数,只需每两分钟调用一次rnd
函数。
This could be as simple as something like (pseudo-code): 这可能像(伪代码)一样简单:
n = rnd()
repeat until finished:
use n for something
sleep for two minutes
n = rnd()
If you want to keep using the same random number for two minutes and generate a new one: 如果要继续使用相同的随机数两分钟并生成一个新的随机数,请执行以下操作:
time t = 0
int n = 0
def sort_of_rnd():
if now() - t > two minutes:
n = rnd()
t = now()
return n
which will continue to return the same number for a two minute period. 它将在两分钟内继续返回相同的数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.