Task dependencies

Gradle runs the tasks a command asked for, plus everything they need, in an order that respects three relations: dependsOn means "run this one first or the result is wrong", mustRunAfter means "if both run, this one later", and finalizedBy means "run this one afterwards, whatever happened". The three are shown below on four tasks that print their own names.

Four tasks and three edges

settings.gradle

rootProject.name = 'shop'

build.gradle

plugins { id 'base' } tasks.register('prepare') { doLast { println 'prepare' } } tasks.register('compile') { dependsOn 'prepare' doLast { println 'compile' } } tasks.register('verify') { mustRunAfter 'compile' doLast { println 'verify' } } tasks.register('report') { doLast { println 'report' } } tasks.register('publish') { dependsOn 'compile', 'verify' finalizedBy 'report' doLast { println 'publish' } }

Run it

gradle -q publish --console=plain --offline --no-daemon

prepare
compile
verify
publish
report

Five tasks, and the order is not the order of the file: prepare came first because compile depends on it, verify came after compile because of mustRunAfter, and report came last although nothing depends on it, because publish finalizes with it.

mustRunAfter alone adds nothing to the graph. Asking for verify by name runs it alone, without compile, because the relation only orders two tasks that are already in the plan:

gradle -q verify --console=plain --offline --no-daemon

verify

dependsOn, mustRunAfter, finalizedBy

relation what it means when to use it
dependsOn the other task runs before this one, and running this one runs it the result of the other task is the input of this one
mustRunAfter ordering only: if both are in the graph, this one runs later two tasks write to the same folder but neither needs the other
finalizedBy the other task runs after this one, even when this one fails cleanup, a report, a stop of a server

A dependency is a graph, and a cycle in it is an error Gradle reports before it runs anything: Circular dependency between the following tasks. The next lesson prints the graph of a real build before it runs.

Related

Article author: Arthur Isaev

Banner image