title: Callback when a periodic task is cancelled and done
body: <p>I have two tasks: The first task (<code>work</code>) is reoccurring and the second task (<code>cleanup</code>) is releases some resources.  The <code>cleanup</code> task should be run exactly once after the reoccurring <code>work</code> task has completed and will not be run again.</p>
  
  <p>My first instinct was something like this:</p>
  
  <pre><code>ScheduledExecutorService service = ...;
  ScheduledFuture&lt;?&gt; future = service.scheduleAtFixedRate(work, ...);
  
  // other stuff happens
  
  future.cancel(false);
  cleanup.run();
  </code></pre>
  
  <p>The problem here is that <code>cancel()</code> returns immediately.  So if <code>work</code> happens to be running, then <code>cleanup</code> will overlap it.</p>
  
  <p>Ideally I would use something like Guava's <code>Futures.addCallback(ListenableFuture future, FutureCallback callback)</code>.  (Guava 15 may have <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/util/concurrent/ListenableScheduledFuture.html">something like that</a>).</p>
  
  <p>In the meantime, how can fire a callback when <code>future</code> is cancelled <em>and</em> <code>work</code> no longer running?</p>