title: Java execute task with a number of retries and a timeout
body: <p>I'm trying to create a method that executes a given task in a maximum amount of time. If it fails to finish in that time, it should be retried a number of times before giving up. It should also wait a number of seconds between each try. Here's what I've come up with and I'd like some critiques on my approach. Is their a simpler way to do this using the <code>ScheduledExecutorService</code> or is my way of doing this suffice?</p>
  
  <pre><code>public static &lt;T&gt; T execute(Callable&lt;T&gt; task, int tries, int waitTimeSeconds, int timeout) 
      throws InterruptedException, TimeoutException, Exception {
  
      Exception lastThrown = null;
      for (int i = 0; i &lt; tries; i++) {
          try {
              final Future&lt;T&gt; future = new FutureTask&lt;T&gt;(task);
              return future.get(timeout, TimeUnit.SECONDS);
          } catch (TimeoutException ex) {
              lastThrown = ex;
          } catch (ExecutionException ex) {
              lastThrown = (Exception) ex.getCause();
          }
          Thread.sleep(TimeUnit.SECONDS.toMillis(waitTimeSeconds));
      }
      if (lastThrown == null) {
          lastThrown = new TimeoutException("Reached max tries without being caused by some exception. " + task.getClass());
      }
      throw lastThrown;
  }
  </code></pre>