Skip to content
Advertisement

Run gradle task after doLast of a other task

I have a variable in my build.gradle (xy) file with an integer value and three simple tasks. The tree tasks are also “bundled” in a fourth task, to call the three tasks one after one. If I call the task callAll, the task callOne should add 5 to the int value, task callTwo should add also 5 the int value, but in a doLast block and finally task callThree prints out the value. It should be 10 but it prints 5, I guess because of the doLast block. But I dont understand why, I declared to call task callThree it mustRunAfter callTwo in the task callAll.

This example is of course a simplified version of a more complex build.gradle I have. How can i get the right output, without changing the three simple tasks?

project.ext{
 xy= 0
}

task callOne(){
 xy = xy + 5
}

task callTwo(){
 doLast{
  xy = xy + 5
 } 
}

task callThree(){
 println "xy : $xy"
}

task callAll(){
 dependsOn 'callOne'
 dependsOn 'callTwo'
 dependsOn 'callThree'

 tasks.findByName('callTwo').mustRunAfter 'callOne'
 tasks.findByName('callThree').mustRunAfter 'callTwo'
}

Advertisement

Answer

A Gradle build runs three distinct phases: Initialization, Configuration and Execution (Documentation).

In the configuration phase, the project and its tasks are configured. During this phase:

  • callOne sets xy = xy + 5
  • callTwo does nothing
  • callThree prints println "xy : $xy"

Tasks are executed in the execution phase of the Gradle build, this means:

  • callOne does nothing
  • callTwo sets xy = xy + 5
  • callThree does nothing

5 is printed rather than 10 since you’re mixing configuration and execution phases.

callAll is more or less only a custom lifecycle task that configures the task graph. In itself, callAll performs no calls to the other tasks and consequently does nothing in the execution phase.

You may get your desired behavior by enclosing all task actions in a doFirst {} or doLast {} block.

Please have a look at Configuration time and execution time for more information.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement