title: Java - ScheduledExecutorService: Execute task at termination
body: <p>I use the <code>ScheduledExecutorService</code> to execute a task at a fixed rate. Here is the contents of my main method:</p>
  
  <pre><code>RemoteSync updater = new RemoteSync(config);
  try  {
      updater.initialise();
      updater.startService(totalTime, TimeUnit.MINUTES);
  } catch (Exception e) {
      e.printStackTrace();
  }
  </code></pre>
  
  <p><code>RemoteSync</code> implements the <code>AutoCloseable</code> (and <code>Runnable</code>) interface, so I initially used <code>try-with-resources</code>, like this:</p>
  
  <pre><code>try (RemoteSync updater = new RemoteSync(config)) {
      ...
  } catch (Exception e) {
     e.printStackTrace();
  }
  </code></pre>
  
  <p>But <code>updater.startService()</code> returns immediately after scheduling the task, so the <code>updater.close()</code> is called prematurely and the application exits. </p>
  
  <p>Here is the <code>startService()</code> method of <code>RemoteSync</code>:</p>
  
  <pre><code>public void startService(int rate, TimeUnit unit) {
      ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
      service =
          scheduledExecutorService.scheduleWithFixedDelay(this, 1L,
          rate,
          unit);
  }
  </code></pre>
  
  <p>Ideally, I would like to have a method like:</p>
  
  <pre><code>scheduledExecutorService.executeAtTermination(Runnable task)
  </code></pre>
  
  <p>This will allow me to call <code>close()</code> when scheduler has actually stopped, unfortunately I am not aware of such a method. </p>
  
  <p>What I can do, is block the <code>startService()</code> method, with something like this:</p>
  
  <pre><code>while (!scheduledExecutorService.isTerminated()) {
      Thread.sleep(10000);
  }
  </code></pre>
  
  <p>but this feels dirty and hackish. </p>
  
  <p>Any suggestion are welcome.</p>