Java Academy Logo

Gradle Tasks and Lifecycle

1. Gradle Lifecycle

Gradle's lifecycle describes how a build runs from start to finish. It has three main phases:

1. Initialization Phase

Gradle determines which projects are involved in the build.

  • Gradle finds the root project (where settings.gradle or settings.gradle.kts lives).
  • It evaluates settings.gradle to discover all included subprojects.
  • It creates a Project object for each project.

Example: A multi-module project creates multiple Project instances here.

2. Configuration Phase

Gradle configures the build for all projects included in the build.

What happens:

  • Gradle runs all the build scripts (build.gradle, build.gradle.kts) to configure tasks.
  • Task objects are created and configured.
  • Dependency graphs for tasks are built.

Output: A fully configured build with all tasks ready, but no tasks have run yet.

3. Execution Phase

Gradle executes only the tasks requested on the command line.

Example: :moduleA:build

2. Gradle Tasks

A Gradle task is a single job in the build process. It could be any task like compiling code, running tests, creating a package or uploading files. These tasks are defined in a build script (build.gradle).

Types of Gradle Tasks

Gradle provides two main types of tasks which are listed below:

1. Built-In Tasks:

Built-In Tasks are tasks that come pre-configured with gradle. Common built-in tasks include:

  • build: It compiles and assembles the project.
  • clean: It deletes the build directory.
  • test: It runs unit tests for the project.
  • jar: It creates a JAR file from the compiled classes.

2. Custom Tasks:

Custom tasks are tasks that we define in our build.gradle file. We can create a task to automate any action that Gradle does not handle by default.

Example:

task helloWorld {
    doLast {
        println 'Welcome to the homePath'
    }
}

Output: This task will print a message when you run it.