title: Delay execution of code in method Java
body: <p>I want to generate random number after every 2 seconds in my java (Android) program continuously for at least 10 minutes. But I just want to pause/delay execution of code in only one method and not the whole program.</p>
  
  <p>I tried using Thread like this -</p>
  
  <pre><code>boolean stop = false;
  int random_number = 0;
  
  while(true){
      if(stop){  //if stop becomes true, then
          return;  //terminate the method
      }
  
      random_number = Math.random(); //generate random number
                                     //which is used bu some other
                                     //part of code
      try {
          Thread.sleep(2000);        //delay the code for 2 secs
      } catch(InterruptedException ex) {  //and handle the exceptions
          Thread.currentThread().interrupt();
      }
  }
  </code></pre>
  
  <p>However, this doesn't work as <code>Thread.sleep</code> stop the whole program execution instead on just stopping execution of code inside method and my whole screen becomes blank.</p>
  
  <p>I also tried using <a href="https://stackoverflow.com/a/15874176/3886922"><code>Handler</code></a> but it didn't work either as it doesn't stop execution of code in my method and instead just stack up.</p>
  
  <p>This will demonstrate the working of it better -</p>
  
  <pre><code>while(true){
      final Handler handler = new Handler();
      handler.postDelayed(new Runnable() {
          @Override
          public void run() {
              System.out.println("After 2 secs"); //this gets printed
                                                 //later
          }
      }, 2000);
      System.out.println("Before 2 secs"); //this gets printed first
  }
  </code></pre>
  
  <p>So the code stacks up making it equivalent to using while loop and make it incredibly slow.</p>
  
  <p>Also, since I'm developing app for Android, I'm running on Java SE 6, so I can't use <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html#scheduleAtFixedRate%28java.lang.Runnable,%20long,%20long,%20java.util.concurrent.TimeUnit%29" rel="nofollow noreferrer"><code>scheduleAtFixedRate</code></a>. Is there any other way in which I can accomplish this?</p>
  
  <p>Thanks a lot!</p>