Asked  7 Months ago    Answers:  5   Viewed   59 times

I am trying to do something in Java and I need something to wait / delay for an amount of seconds in a while loop.

while (true) {
    if (i == 3) {
        i = 0;
    }

    ceva[i].setSelected(true);

    // I need to wait here

    ceva[i].setSelected(false);

    // I need to wait here

    i++;
}

I want to build a step sequencer and I'm new to Java. Any suggestions?

 Answers

75

If you want to pause then use java.util.concurrent.TimeUnit:

TimeUnit.SECONDS.sleep(1);

To sleep for one second or

TimeUnit.MINUTES.sleep(1);

To sleep for a minute.

As this is a loop, this presents an inherent problem - drift. Every time you run code and then sleep you will be drifting a little bit from running, say, every second. If this is an issue then don't use sleep.

Further, sleep isn't very flexible when it comes to control.

For running a task every second or at a one second delay I would strongly recommend a ScheduledExecutorService and either scheduleAtFixedRate or scheduleWithFixedDelay.

For example, to run the method myTask every second (Java 8):

public static void main(String[] args) {
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS);
}

private static void myTask() {
    System.out.println("Running");
}

And in Java 7:

public static void main(String[] args) {
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            myTask();
        }
    }, 0, 1, TimeUnit.SECONDS);
}

private static void myTask() {
    System.out.println("Running");
}
Tuesday, June 1, 2021
 
Dail
answered 7 Months ago
52

The setTimeout() function is non-blocking and will return immediately. Therefore your loop will iterate very quickly and it will initiate 3-second timeout triggers one after the other in quick succession. That is why your first alerts pops up after 3 seconds, and all the rest follow in succession without any delay.

You may want to use something like this instead:

var i = 1;                  //  set your counter to 1

function myLoop() {         //  create a loop function
  setTimeout(function() {   //  call a 3s setTimeout when the loop is called
    console.log('hello');   //  your code here
    i++;                    //  increment the counter
    if (i < 10) {           //  if the counter < 10, call the loop function
      myLoop();             //  ..  again which will trigger another 
    }                       //  ..  setTimeout()
  }, 3000)
}

myLoop();                   //  start the loop

You could also neaten it up, by using a self invoking function, passing the number of iterations as an argument:

(function myLoop(i) {
  setTimeout(function() {
    console.log('hello'); //  your code here                
    if (--i) myLoop(i);   //  decrement i and call myLoop again if i > 0
  }, 3000)
})(10);                   //  pass the number of iterations as an argument
Tuesday, June 1, 2021
 
CodeCaster
answered 7 Months ago
91

Thread has a method that does that for you join which will block until the thread has finished executing.

Tuesday, June 1, 2021
 
laurent
answered 7 Months ago
28

Migrated whole implementation to use apache HTTP client as it has special APIs for better control. But it didn't help. Even with apache HTTP client, I could see these waiting connection threads.

Finally found hint on redhat website for JBOSS HTTP connector configuration. Configured thread pool for HTTP connector and it solved the issue:

<subsystem xmlns="urn:jboss:domain:threads:1.1"> 
    <thread-factory name="http-connector-factory" group-name="uq-thread-pool" thread-name-pattern="HTTP-%t" priority="9"/> 
    <unbounded-queue-thread-pool name="uq-thread-pool"> 
        <max-threads count="5"/> 
        <keepalive-time time="5" unit="seconds"/> 
        <thread-factory name="http-connector-factory"/> 
    </unbounded-queue-thread-pool> 
</subsystem> 

<subsystem xmlns="urn:jboss:domain:web:2.2" default-virtual-server="default-host" native="false">

    <connector name="http" protocol="org.apache.coyote.http11.Http11NioProtocol" scheme="http" socket-binding="http" executor="uq-thread-pool"/> 
    ....
    ....
Saturday, August 21, 2021
 
noir
answered 4 Months ago
93

Don't know the context, but it might be that the page has not been loaded yet completely - you might try putting

if (document.getElementById("ismForm")) {
    setTimeout("submitForm()", 5000); // set timout 
}

in body onLoad() event. As another thing, try putting as simple alert before setTimeout and at the start of submitForm() to confirm the timeout is getting fired in the first place.

Thursday, October 14, 2021
 
BlueNile
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share