title: Java: execute Runnable fixed number of times
body: <p>So I have a piece of code that I want to execute repeatedly. I get this part. The problem is that I want to execute the code at fixed intervals, but only a fixed number (in this case 1440) times. </p>
  
  <p>Any ideas how I'd do that?</p>
  
  <p>Here's the code:</p>
  
  <pre><code>import java.util.concurrent.Executors;
  import java.util.concurrent.ScheduledExecutorService;
  import java.util.concurrent.TimeUnit;
  
  
  public class Simulator {
  
      public static int TICK = 10;
      public static int NUM_OF_SERVERS = 3;
      public static int LENGTH_OF_SIMULATION = 1440;
  
      public static void main(String[] args) {
  
  
          final MultiQueueControlSystem multiController = MultiQueueControlSystem.getInstance();
          final SingleQueueControlSystem singleController = SingleQueueControlSystem.getInstance();
  
          multiController.generateQueuesAndServers(NUM_OF_SERVERS);
          singleController.generateQueuesAndServers(NUM_OF_SERVERS);
  
          final ScheduledExecutorService ticker = Executors.newSingleThreadScheduledExecutor();
  
          ticker.scheduleAtFixedRate(new Runnable() {
  
              int currentTime = 0;
  
              public void run() {
  
                  if(currentTime &lt; LENGTH_OF_SIMULATION) {
                      currentTime = currentTime + 1;
                  } else {
                      ticker.shutdown();
                      return;
                  }
  
                  multiController.customerArrival();
                  multiController.allocateCustomersToServers();
                  multiController.removeFinishedCustomersFromServers();
  
                  singleController.customerArrival();
                  singleController.allocateCustomersToServers();
                  singleController.removeFinishedCustomersFromServers();
              }
          }, 1, TICK, TimeUnit.MILLISECONDS);
      }
  }
  </code></pre>