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
doLast
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”
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:actionsEgdoFirst-1 - will be executed FIRSTdoFirst-2 will be executed SECONDdoFirst-3 will be executed THIRDdoLast will be executed FOURTHBUILD SUCCESSFUL in 359ms1 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