Skip to main content

Gradle : How to make a task that depends on another task

How to write a Gradle Task

A gradle task can be written in the following two ways

task hello(){
doLast(){
println "Hello World"
}
}

Or you can write a task as follows

task hello << {
println "Hello World"

}

Here in example 2, << operator is simply an alias for doLast.

Write a Gradle Task that depends on another Gadle Task

Lets take an example of the following gradle file.

build.gradle

task openFile(){
doLast{
println "Open file"
}
}

task readFile(dependsOn : 'openFile'){
doLast{
println "Read File"
}
}

task closeFile(dependsOn : ['openFile','readFile']){
doLast{
println "Close File"
}
}

Here in this example, we have three tasks

  1. openFile - that will open a file
  2. readFile - that will read a file
  3. closeFile - that will close a file.

Now, for able to read from a file, we should first open a file, so readFile depends on openFile, also a file will be closed after reading a file so closeFile task depends on both openFile and readFile

Now if we run the tasks, it will give the following outputs

> gradle -q openFile or gradle -q oF
> Open file

> gradle -q readFile or gradle -q cF
> Open file
> Read File

gradle -q closeFile or gradle -q cF
> Open file
> Read File
> Close File

A gradle task is loaded in a lazy manner that means you can define a task anywhere in the build file. The task dependency is looked in execution phase and not in configuration phase.

Let's check it by the following example


// Task B does not exists here but will be resolved at runtime.
task A(dependsOn : 'B'){
doLast(){
println "A"
}
}

task B(){
doLast(){
println "B"
}
}


Also Read

Comments