Groovy & Gradle: JVM Automation and Build Engineering · Урок

Задачи и жизненный цикл сборки

Определяйте и управляйте задачами Gradle, изучайте их зависимости и основные этапы жизненного цикла сборки.

Урок 3 из 412 шагов

«Задачи и жизненный цикл сборки» — бесплатный урок Groovy & Gradle: JVM Automation and Build Engineering на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Groovy & Gradle: JVM Automation and Build Engineering, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Groovy & Gradle: JVM Automation and Build Engineering содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

What are Gradle Tasks?

Welcome! In this lesson, we'll dive into Gradle Tasks, the fundamental units of work in any Gradle build.

  • A task represents a single, atomic piece of work that Gradle performs.
  • Think of tasks as actions like 'compile code', 'run tests', 'clean build directory', or 'deploy application'.
  • They are the building blocks that make up your entire build process.

Discovering Built-in Tasks

Gradle comes with many built-in tasks. You can list all available tasks for your project using the command line:

gradle tasks

This command shows a categorized list of tasks, including those provided by plugins and any custom tasks you define. It's a great way to explore what your build can do!

Defining Your First Task

Creating your own custom task is straightforward in your build.gradle file. Let's define a simple task:

The task keyword is used, followed by the task's name. The curly braces {} define the task's actions.

task helloWorld {
    println "Hello from CoddyKit Gradle!"
}

Running Custom Tasks

To execute a custom task, you simply run Gradle from your terminal, specifying the task name:

gradle helloWorld

When you run the example from the previous scene, you'll see "Hello from CoddyKit Gradle!" printed in the console.

Task Actions: doLast & doFirst

Tasks can have multiple actions. You can define these actions using doLast and doFirst blocks.

  • doLast: Adds an action to be executed at the end of the task.
  • doFirst: Adds an action to be executed at the beginning of the task.

These are useful for organizing complex task logic.

task myGreet {
    doFirst {
        println "Preparing to greet..."
    }
    doLast {
        println "Hello, CoddyKit!"
    }
}

Chaining Tasks with dependsOn

Often, one task must complete before another can start. Gradle handles this with task dependencies using the dependsOn keyword.

If task 'B' depends on task 'A', then 'A' will always run before 'B'. This ensures operations happen in the correct order.

task prepare {
    doLast {
        println "Preparation complete."
    }
}

task build(dependsOn: prepare) {
    doLast {
        println "Build finished."
    }
}

Understanding the Build Lifecycle

Every time you run a Gradle command, it goes through a distinct build lifecycle, consisting of three main phases:

  1. Initialization: Sets up the build environment.
  2. Configuration: Evaluates build scripts and configures tasks.
  3. Execution: Runs the configured tasks.

Understanding these phases is key to writing effective Gradle builds.

Phase 1: Initialization

The Initialization Phase is where Gradle determines which projects are participating in the build.

  • It evaluates the settings.gradle file (if present).
  • This file defines the project hierarchy for multi-project builds.
  • Gradle creates a Project instance for each project involved.

This phase essentially sets the stage for the build.

Phase 2: Configuration

During the Configuration Phase, all build.gradle scripts for the projects are evaluated.

  • Tasks are created and configured.
  • Important: Any code directly in a task block (not inside doLast or doFirst) runs during this phase, regardless of whether the task will actually be executed.

This is where tasks' properties and dependencies are set up.

task configExample {
    println "This message runs during Configuration!"
    doLast {
        println "This message runs during Execution!"
    }
}

Phase 3: Execution

The final phase is the Execution Phase. This is where the actual work happens!

  • Gradle determines which tasks need to run based on your command and task dependencies.
  • It then executes the doFirst and doLast actions (and any other actions) of those selected tasks.
  • Tasks are executed in the correct order, respecting their dependencies.

This is when your code compiles, tests run, and artifacts are built.

Lifecycle Check

Let's test your understanding of Gradle's build lifecycle!

Tasks & Lifecycle Recap

Great job! You've learned the core concepts of Gradle tasks and the build lifecycle:

  • Tasks are the fundamental units of work.
  • You can define custom tasks and chain them with dependsOn.
  • The Gradle build proceeds through three phases: Initialization, Configuration, and Execution.
  • Code directly in a task block runs during Configuration, while doFirst/doLast actions run during Execution.

Next, we'll explore how Gradle manages external dependencies!

Можно начать бесплатно

Изучай Groovy с ИИ-репетитором — бесплатно

Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.

Курсы
12
Уроки
48

Часто задаваемые вопросы

Урок «Задачи и жизненный цикл сборки» бесплатный?

Да — полный текст урока «Задачи и жизненный цикл сборки» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Groovy & Gradle: JVM Automation and Build Engineering, подпишись на CoddyKit PRO. Курс Groovy & Gradle: JVM Automation and Build Engineering содержит 4 уроков всего.

Чему я научусь в уроке «Задачи и жизненный цикл сборки»?

Определяйте и управляйте задачами Gradle, изучайте их зависимости и основные этапы жизненного цикла сборки. Ты практикуешь Groovy & Gradle: JVM Automation and Build Engineering с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Groovy & Gradle: JVM Automation and Build Engineering?

Предыдущий опыт не требуется. Groovy & Gradle: JVM Automation and Build Engineering на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.

Сколько времени занимает урок «Задачи и жизненный цикл сборки»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Groovy & Gradle: JVM Automation and Build Engineering?

Да. Каждый урок Groovy & Gradle: JVM Automation and Build Engineering включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Установка Gradle и CLI
  2. Структура проекта Gradle
  3. Задачи и жизненный цикл сборки
  4. Сборки нескольких проектов и файл настроек
← Назад к Groovy & Gradle: JVM Automation and Build Engineering