Robert Cardona Robert Cardona - 1 year ago 128
Java Question

Java Loop every minute

I want to write a loop in Java that firs starts up and goes like this:

while (!x){
//wait one minute or two

//execute code

I want to do this so that it does not use up system resources. What is actually going on in the code is that it goes to a website and checks to see if something is done, if it is not done, it should wait another minute until it checks again, and when its done it just moves on. Is their anyway to do this in java?

Answer Source

Use Thread.sleep(long millis).

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

One minute would be (60*1000) = 60000 milliseconds.

For example, this loop will print the current time once every 5 seconds:

    try {
        while (true) {
            System.out.println(new Date());
            Thread.sleep(5 * 1000);
    } catch (InterruptedException e) {

If your sleep period becomes too large for int, explicitly compute in long (e.g. 1000L).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download