Wait for the execution of a task to complete before running another task

In my build.gradle file I have a couple of tasks:

// pseudo code
taskA {
// long running task - integration tests
println “A”
}

taskB {
dependsOn "taskA"
println “B”
}

taskC {
dependsOn "taskB"
println “B”
}

When I run the code, I see A->B->C printout, as expected. However, my
case requires that task C should wait after taskA (long-running
integration tests) is complete before it starts. Currently "ABC"
printout is instanteneous, so I believe gradle orders just starting of
tasks execution.

I have tried

taskB.mustRunAfter taskA
taskC.mustRunAfter taskB

…but result is exactly the same.

Does anyone have any ideas how waiting for one task to finish execution can be implemented in gradle?

This is a common misconception, because the “obvious” way to specify a task body isn’t doing what you think. All of those printlns are executing at “configuration time” instead of “execution time”, so task dependencies aren’t taken into account at that point. This is done so that Gradle has a full view of all the task configurations and dependencies before it starts executing tasks. A simple fix for this example would be to wrap each println with “doLast { … }”.

Thanks a lot, David.

Digging into this direction, I have found that using
gradle.taskGraph.afterTask { Task task, TaskState state ->

works just as well.

Hey Alexey,

the problem with your build snippet is, that you put the println
statements in the configuration block of the task and not into a
doLast/doFirst action.

Checkout the build lifecycle chapter in the gradle userguide for further
details: https://docs.gradle.org/current/userguide/build_lifecycle.html

1 Like

Hey Rene,

Thanks a lot for your input