Task execution: need help to understand


(aleks marchanka) #1

Have in my gradle.build

task hello {
    doLast {
        println 'Hello World!'
    }
}

task count {
    println "one"
    doLast{
        4.times {print "$it "}
    }
    println "two"
    doFirst{
        2.times {println "$it - 1 "}
    }
    3.times {println( "$it -3")}
}

task intro(dependsOn: hello){
    doLast{
        println("I'm Gradle!")
    }
}

run in shell

gradle intro

the output was

one
two
0 -3
1 -3
2 -3
:hello
Hello World!
:intro
I'm Gradle!

BUILD SUCCESSFUL

but that’s not correct. I expected the output:

:hello
Hello World!
:intro
I'm Gradle!

BUILD SUCCESSFUL

Please help to understand why I have the first one output instead of second one.


(davidmichaelkarr) #2

This is just about the most FAQ from developers new to Gradle.

I’m not an expert, but I’ll give you a rough idea of what’s happening here.

Gradle executes the build script in two “phases”, being the “configuration” phase and the “execution” phase.

In the “configuration” phase, it executes all “raw” statements outside of task definitions and statements inside of task definitions, but outside of “doLast” (and “doFirst”, I suppose).

In the “execution” phase, when it’s determined the entire task dependency tree, it executes the “doLast” (and “doFirst”) blocks of tasks in dependency order.

In your test case, all of the unexpected output is defined outside of “doLast”/“doFirst”, so it is executed unconditionally in the “configuration” phase.


(aleks marchanka) #3

Many thanks for the reply, David!