Skip to content

Gradle Task actions and ordering

In Gradle, tasks are the fundamental units of work, and their execution is managed through specific actions and ordering rules. Understanding how to define task behavior and control the sequence in which tasks run is essential for creating efficient build logic^[600-developer-gradle-gradle-build.md].

Task Actions

Tasks can contain logic that executes during the build's execution phase. While standard code blocks inside a task definition run during the configuration phase, specific action methods are used to define runtime behavior^[600-developer-gradle-gradle-build.md].

  • doFirst: Adds an action to the beginning of the task's action list^[600-developer-gradle-gradle-build.md].
  • doLast: Adds an action to the end of the task's action list^[600-developer-gradle-gradle-build.md].

Actions defined within doFirst and doLast blocks are invoked only when the task is actually executed, distinguishing them from configuration logic^[600-developer-gradle-gradle-build.md].

Task Ordering and Dependencies

Gradle provides mechanisms to define the order in which tasks are processed, either through hard dependencies or ordering constraints.

Task Dependencies (DependsOn)

Tasks can declare dependencies on other tasks using the dependsOn method^[600-developer-gradle-gradle-build.md]. This ensures that the specified tasks complete successfully before the current task begins. Dependencies create a hard constraint; if task B depends on task A, task A must run before task B^[600-developer-gradle-gradle-build.md].

Execution Ordering (mustRunAfter)

In addition to strict dependencies, Gradle allows for "soft" ordering constraints using mustRunAfter^[600-developer-gradle-gradle-build.md].

This method specifies that a task should run after another, but it does not create a strict dependency execution requirement. For example, if task B uses mustRunAfter task A, task B will only run after task A if both tasks are scheduled for execution in the current build graph^[600-developer-gradle-gradle-build.md].

Task Inputs and Outputs

Gradle uses the concept of inputs and outputs to manage task efficiency and incrementality.

  • TaskInputs: Represents the data or resources a task consumes^[600-developer-gradle-gradle-build.md].
  • TaskOutputs: Represents the data or resources a task produces^[600-developer-gradle-gradle-build.md].

By defining inputs and outputs, Gradle can determine if a task is up-to-date. If the inputs and outputs have not changed since the last execution, Gradle may skip the task (UP-TO-DATE), optimizing build performance^[600-developer-gradle-gradle-build.md].

Sources

^[600-developer-gradle-gradle-build.md]