title: Wait for task to finish before terminating in ScheduledThreadPoolExecutor
body: <p>I have a <code>Runnable</code> implementation that does some work which might take some time and  I am trying to schedule it using <code>ScheduledThreadPoolExecutor</code>with <code>scheduleAtFixedRate</code> method. Now I want to ensure that shut down is graceful that means, Before terminating, task should be allowed to run completely. I have written following code for shutdown.</p>
  
  <pre><code> public void shutDown() throws Exception {
      try {
          LOG.info("Gracefully shutting down executor");
          executor.shutdown();
          if (!executor.awaitTermination(SHUTDOWN_TIMEOUT, TimeUnit.SECONDS)) {
              // cancels currently executing tasks.
              LOG.info("Executor is still alive. Forcing executor thread pool to shut down");
              executor.shutdownNow();
  
              // Wait a while for tasks to respond to being cancelled
              if (!executor.awaitTermination(SHUTDOWN_TIMEOUT, TimeUnit.SECONDS)) {
                  LOG.fatal("Executor thread pool did not terminate");
                  throw new Exception("Unable to shut down executor thread pool forcefully");
              }
              LOG.info("Executor shut down.");
          }
      } catch (Exception e) {
          LOG.error("Exception shutting down executor", e);
          throw e;
      }
  }
  </code></pre>
  
  <p>But problem with this is, I have to specify time to wait explicitly and I can not predict time taken by task in advance. Is there a way to make executor wait indefinitely until executing task finishes without having to mention time to wait? Or is there a better way to work on above scenario?</p>
  
  <p>Thanks</p>
  
  <p>Jitendra</p>