title: Guarantee That a Particular Gradle Task is Run
body: <p>Given the "build.gradle" file below I want to make sure that <code>stopServer</code> is run when I call <code>testServerLifecycle</code>. Currently if the <code>runTestOnServer</code> task fails the build stops. 
  If <code>runTestOnServer</code> is the only thing on the task graph I do not want to run <code>stopServer</code>.</p>
  
  <p><strong>build.gradle</strong></p>
  
  <pre><code>tast startServer {}
  
  task runTestOnServer {
      dependsOn startServer
  }
  
  tast stopServer {}
  
  task testServerLifecycle {
      dependsOn runTestOnServer
      finalizedBy stopServer
  }
  </code></pre>
  
  <p>Is this type of functionality supported by Gradle? What can I do ensure that <code>stopServer</code> is run when <code>testServerLifecycle</code> is on the task graph? </p>
  
  <p><em><strong>Details:</strong> Gradle 1.9</em></p>
  
  <hr>
  
  <h2>Solution</h2>
  
  <pre><code>gradle.taskGraph.afterTask { Task task, TaskState state -&gt;
      if (task == runTestOnServer
              &amp;&amp; state.failure
              &amp;&amp; gradle.taskGraph.getAllTasks().contains(stopServer)) {
          println "----------------- Stopping Server -----------------"
          tasks.stopServer.execute()
      }
  }
  </code></pre>
  
  <p>I was not able to use <code>finalizedBy</code> on the 'runTestOnServer' task, because I wanted to run 'stopServer' <strong>if and only if</strong> 'stopServer' would have run normaly; using <code>finalizedBy</code> would have forced it to run every time. </p>
  
  <p><em>It should be noted that this gets run after every task.</em></p>