Task Actions in Gradle (Execution Phase)
Overview
Gradle tasks are composed of actions, which are units of work that are executed in a specific order. This note covers the key methods for defining actions in Gradle tasks:
doLast
doFirst
Key Methods for Defining Task Actions
The doLast
method adds an action to the end of a task's execution phase.
This action is executed after all other actions defined in the task have completed.
Usage Example:
tasks.register("exampleTask") {
doLast {
println("This action runs after the main task actions.")
}
}
Syntax: <<
Operator '<<' IS do last
Note: the "<<" is a shorthand notation for "doLast"
task B << {
println 'action'
}
doFirst
The doFirst
method adds an action to the beginning of a task's execution phase. This action is executed before all other actions defined in the task.
Usage Example:
tasks.register("exampleTask") {
doFirst {
println("This action runs before the main task actions.")
}
}
Key Points
- Execution Order:
doFirst
actions are executed first.doLast
actions are executed last.
Example in Context
In a task that prepares a file for logging test results, these methods can ensure the file is properly managed before and after the main task actions:
tasks.register("actionsEg") {
doFirst {
println("doFirst-3 will be executed THIRD")
}
doFirst {
println("doFirst-2 will be executed SECOND")
}
doLast {
println("doLast will be executed FOURTH")
}
doFirst {
println("doFirst-1 - will be executed FIRST")
}
}
Glass thought Sandbox Snapshot
Command to reproduce:
gt.sandbox.checkout.commit 3102345 \
&& cd "${GT_SANDBOX_REPO}" \
&& cmd.run.announce "./gradlew actionsEg"
Recorded output of command:
> Task :lib:actionsEg
doFirst-1 - will be executed FIRST
doFirst-2 will be executed SECOND
doFirst-3 will be executed THIRD
doLast will be executed FOURTH
BUILD SUCCESSFUL in 359ms
1 actionable task: 1 executed
Reverse order
Multiple doFirst
and doLast
blocks are executed in the reverse order they are defined
- Just avoid having multiple doFirst or doLast in the same task
Children
Backlinks