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

Определение пользовательских задач

Пишите собственные задачи Gradle с использованием Groovy или Kotlin DSL для автоматизации отдельных этапов сборки.

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

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

Custom Tasks: Why & How?

Why define your own Gradle tasks? They let you automate unique steps not covered by standard plugins. Think of custom tasks as recipes for specific build actions.

This lesson will show you how to craft them to extend Gradle's capabilities!

Your First Custom Task

The simplest way to create a custom task is directly in your build.gradle file. Use the task keyword followed by your task's name.

Let's create a task named helloCustom:

// build.gradle
task helloCustom {
    doLast {
        println 'Hello from a custom task!'
    }
}

Task Actions: doLast & doFirst

Tasks can have multiple actions. You can define them using doFirst and doLast blocks. These blocks specify code to run before or after the task's main actions.

// build.gradle
task orderedActions {
    doFirst {
        println 'This runs first!'
    }
    doLast {
        println 'This runs last!'
    }
    doLast { // Can have multiple doLast/doFirst
        println 'This runs after the previous doLast!'
    }
}

Beyond Inline: Custom Task Classes

For more complex logic or reusability across projects, you'll want to define a custom task as a class. This allows for better organization, testing, and property management.

  • Encapsulation: Keep task logic in one place.
  • Reusability: Share tasks between different projects.
  • Configuration: Define properties for customization.

Writing a Custom Task Class

Custom task classes extend Gradle's DefaultTask. You define the task's actions within a method, often annotated with @TaskAction.

Create a file named src/main/groovy/com/coddykit/tasks/MyGreetingTask.groovy:

package com.coddykit.tasks

import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction

class MyGreetingTask extends DefaultTask {

    @TaskAction
    def greet() {
        println "Hello from MyGreetingTask!"
    }
}

Using Your Custom Task Class

To use your custom task class, you need to tell Gradle where to find it and then register an instance of it. First, add the Groovy plugin to compile your task class.

Update your build.gradle:

// build.gradle
plugins {
    id 'groovy' // To compile Groovy task classes
}

repositories {
    mavenCentral()
}

dependencies {
    // Required for DefaultTask
    implementation gradleApi()
    // If your task uses Groovy
    implementation 'org.codehaus.groovy:groovy-all:3.0.10'
}

// Register our custom task
tasks.register('myGreeting', com.coddykit.tasks.MyGreetingTask)

Executing the Class-Based Task

Now that your custom task class is defined and registered in build.gradle, you can execute it just like any other Gradle task from your terminal.

Run the command:

gradle myGreeting

Task Types vs. Definitions

It's important to distinguish between defining a task type (the class) and defining a task instance (registering it).

  • Task Type: The MyGreetingTask class itself, which extends DefaultTask. It defines what the task can do.
  • Task Definition: tasks.register('myGreeting', MyGreetingTask). This creates a specific task named 'myGreeting' of that type.

Custom Task Quiz

You've learned how to create custom tasks. Let's test your understanding!

Defining Custom Tasks Recap

Great job! You've learned how to define custom Gradle tasks:

  • Inline Tasks: Using task name { doLast { ... } } for simple, script-local actions.
  • Task Actions: Controlling execution order with doFirst and doLast.
  • Custom Task Classes: Extending DefaultTask for reusable, organized, and configurable task logic.
  • Registering Tasks: Using tasks.register() to create instances of your custom task classes.

Next, we'll dive deeper into task types and how to configure properties for more dynamic tasks!

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

Урок «Определение пользовательских задач» бесплатный?

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

Чему я научусь в уроке «Определение пользовательских задач»?

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

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

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

Сколько времени занимает урок «Определение пользовательских задач»?

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

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

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

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

  1. Определение пользовательских задач
  2. Типы и действия задач
  3. Свойства и настройка задач
  4. Инкрементальные задачи и проверки актуальности
← Назад к Groovy & Gradle: JVM Automation and Build Engineering