+ 1
How to iterate a for loop with system time ?
I want my loop to execute every 2 minutes. when I put this parameter,I get no output till the time iteration is over.. I want the outputs for every iteration to be visible as the output. How can I do this?
5 Respostas
+ 1
Basically one of the best ways to do this in java is a...
Thread.sleep()
method. Its like a wait() method but most programmers like this more.
Whats the diffrence between wait() and Thread.sleep()?
Its pretty simple... A Thread.sleep() makes, as the name said, that the programm sleeps for a user oriented time. It makes also your "chip" empty.
The wait() method just wait for a current time.
So in the () you will add the time in millisec
2 minutes = Thread.sleep(2*60*1000)
The good thing about it this is you can just add this method in the loop.
For example a for loop:
import java.util.Scanner;
public class TimeRelais {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
try {
for(int i = 0; i <= x; i++) {
Thread.sleep(120*1000);
System.out.println("This is an example.");
}
}
catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
Interrupted Exeption here:
https://www.google.ch/amp/www.yegor256.com/2015/10/20/interrupted-exception.amp.html
I hope i didn't missunderstood you ;).
Note:
It doesn't work for big numbers of time or just use long.
+ 1
the problem is I do not get any output on screen while the thread is on sleep mode. my objective is to get a different output every two minutes.. I m not getting that.
0
@Vaenzelektron thanks for the answer.. but it not solve my query.. my loop is as follows
for (int i=0;i <2;i++){
for (int j=1;j>0;j--){
createpoint (arr [j][i],arr [j--][i]);
/*I want this function to execute and then the for loop to again run after two minutes for the next set of array indexes*/
}
}
0
Where's the problem?
I unterstood you like this little graphic:
______________
| Start Program |
\_____ _____/
___| |___
_______ LOOP----------------After LOOP
/ | |
| Thread.sleep END
\_________/
0
Sorry but I never used something like that in my carrer yet. When you know it please let me know :)