Reputation: 19612
for(int i = 1; i < 10000; i++) {
Command nextCommand = getNextCommandToExecute();
}
I want to run the above program for 60 minutes. So instead of for loop I need to do something like-
long startTime = System.nanoTime();
do{
Command nextCommand = getNextCommandToExecute();
} while (durationOfTime is 60 minutes);
But I am not sure, how should I make this program to run for 60 miniutes.
Upvotes: 1
Views: 111
Reputation: 50087
You could use:
long startTime = System.nanoTime();
do {
Command nextCommand = getNextCommandToExecute();
} while ((System.nanoTime() - startTime) < 60 * 60 * 1000000000L);
Please note System.nanoTime()
is slightly different from using System.currentTimeMillis()
not only in the scale, but also in what it measures: System.nanoTime()
is the elapsed time, and System.currentTimeMillis()
is the system time (wall clock). If the system time changes, System.currentTimeMillis()
doesn't work as expected. (This doesn't apply to summertime change however, as the returned value is UTC / GMT.)
1000000000L
nanoseconds is one second. Please note the L
for long
. In Java 7 you could also write the more readable 1_000_000_000L
.
Upvotes: 0
Reputation: 802
long startTime = System.currentTimeMillis();
do{
Command nextCommand = getNextCommandToExecute();
}while (startTime < startTime+60*60*1000);
Upvotes: 0
Reputation: 5661
try the following:
long startTime = System.currentTimeMillis();
long endTime = startTime + (60*60*1000);
while(System.currentTimeMillis() <= endTime) {
Command nextCommand = getNextCommandToExecute();
}
One drawback with this method is if the Command
you are trying to execute runs past the 60 minute timer or never finishes at all. If this behavior is not allowed, you are better off implementing a thread that interrupts whatever thread is running this loop.
Upvotes: 1
Reputation: 5094
long startTime = System.currentTimeMillis();
do
{
//stuff
} while (System.currentTimeMillis() - startTime < 1000*60*60);
Upvotes: 2
Reputation: 691635
Launch a background thread that sleeps for 60 minutes and exits:
Runnable r = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(60 * 60 * 1000L);
}
catch (InterruptedException e) {
// ignore: we'll exit anyway
}
System.exit(0);
}
}
new Thread(r).start();
<your original code here>
Upvotes: 4