Sub topic 10
Gradle Tasks and the Task Graph
Gradle does all of its work through tasks. A task is one named piece of work, such as compiling code, running tests, or building a JAR file. This chapter shows how to list tasks, write your own, and see how Gradle decides which tasks to run.
Listing the Tasks You Have
The plugins in your build script add tasks for you. The application plugin from the last chapter adds tasks like compileJava, test, jar, and run. To see them all, ask Gradle:
./gradlew tasksGradle prints the tasks in groups, such as "Build tasks" and "Application tasks". Each task has a short description next to it.
Writing Your Own Task
You can add tasks in build.gradle.kts. Add this at the bottom of the file:
tasks.register("hello") {
group = "custom"
description = "Prints a greeting"
doLast {
println("Hello from Gradle")
}
}tasks.registercreates a new task namedhello.groupanddescriptioncontrol where and how it shows up in./gradlew tasks.doLastholds the code that runs when the task runs.
Run it with ./gradlew hello.
Tasks That Depend on Other Tasks
A task can need another task to finish first. This need is called a dependency between tasks. You declare it with dependsOn:
tasks.register("goodbye") {
group = "custom"
description = "Says goodbye after saying hello"
dependsOn("hello")
doLast {
println("Goodbye from Gradle")
}
}When you run ./gradlew goodbye, Gradle runs hello first, then goodbye:
> Task :hello
Hello from Gradle
> Task :goodbye
Goodbye from GradleThe Task Graph
Gradle links all tasks and their dependencies into a task graph. The task graph is a map showing which tasks must run before which. When you ask for one task, Gradle follows the map, finds every task it needs, and runs each one once, in the right order.
The build task is a good example. You never write its steps yourself. The Java plugin wires them together:
The classes task appears twice in the map, but Gradle runs it only once.
To see which tasks would run without running them, use a dry run:
./gradlew build --dry-runYou can also skip a task with -x. For example, ./gradlew build -x test builds without running tests.
Exercise
You add a task named "report" with dependsOn("goodbye"). Which tasks run, and in what order, when you type ./gradlew report?
Show answer
Three tasks run, in this order: hello, goodbye, report. Gradle follows the task graph back from report. It finds that goodbye needs hello, so hello runs first.
Exercise
Which command shows the tasks that ./gradlew build would run, without running them?
Show answer
./gradlew build --dry-run (the short form is -m).