任务代表构建执行的某些独立工作单元,例如编译类、创建 JAR、生成 Javadoc 或将存档发布到存储库。

写作任务1

在阅读本章之前,建议您首先阅读学习基础知识并完成教程

列出任务

项目中的所有可用任务都来自 Gradle 插件和构建脚本。

您可以通过在终端中运行以下命令来列出项目中的所有可用任务:

$ ./gradlew tasks

让我们以一个非常基本的 Gradle 项目为例。该项目具有以下结构:

gradle-project
├── app
│   ├── build.gradle.kts    // empty file - no build logic
│   └── ...                 // some java code
├── settings.gradle.kts     // includes app subproject
├── gradle
│   └── ...
├── gradlew
└── gradlew.bat
gradle-project
├── app
│   ├── build.gradle    // empty file - no build logic
│   └── ...             // some java code
├── settings.gradle     // includes app subproject
├── gradle
│   └── ...
├── gradlew
└── gradlew.bat

设置文件包含以下内容:

settings.gradle.kts
rootProject.name = "gradle-project"
include("app")
settings.gradle
rootProject.name = 'gradle-project'
include('app')

目前,app子项目的构建文件为空。

要查看子项目中可用的任务app,请运行./gradlew :app:tasks

$ ./gradlew :app:tasks

> Task :app:tasks

------------------------------------------------------------
Tasks runnable from project ':app'
------------------------------------------------------------

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in project ':app'.
dependencies - Displays all dependencies declared in project ':app'.
dependencyInsight - Displays the insight into a specific dependency in project ':app'.
help - Displays a help message.
javaToolchains - Displays the detected java toolchains.
kotlinDslAccessorsReport - Prints the Kotlin code for accessing the currently available project extensions and conventions.
outgoingVariants - Displays the outgoing variants of project ':app'.
projects - Displays the sub-projects of project ':app'.
properties - Displays the properties of project ':app'.
resolvableConfigurations - Displays the configurations that can be resolved in project ':app'.
tasks - Displays the tasks runnable from project ':app'.

我们观察到,目前只有少量的帮助任务可用。这是因为 Gradle 的核心仅提供分析构建的任务。其他任务,例如构建项目或编译代码的任务,是通过插件添加的。

让我们通过将Gradle 核心base插件添加到app构建脚本来探索这一点:

app/build.gradle.kts
plugins {
    id("base")
}
app/build.gradle
plugins {
    id('base')
}

base插件添加了中心生命周期任务。现在,当我们运行时./gradlew app:tasks,我们可以看到assemblebuild任务可用:

$ ./gradlew :app:tasks

> Task :app:tasks

------------------------------------------------------------
Tasks runnable from project ':app'
------------------------------------------------------------

Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
clean - Deletes the build directory.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in project ':app'.
dependencies - Displays all dependencies declared in project ':app'.
dependencyInsight - Displays the insight into a specific dependency in project ':app'.
help - Displays a help message.
javaToolchains - Displays the detected java toolchains.
outgoingVariants - Displays the outgoing variants of project ':app'.
projects - Displays the sub-projects of project ':app'.
properties - Displays the properties of project ':app'.
resolvableConfigurations - Displays the configurations that can be resolved in project ':app'.
tasks - Displays the tasks runnable from project ':app'.

Verification tasks
------------------
check - Runs all checks.

任务成果

当 Gradle 执行任务时,它会通过控制台为任务标记结果。

作者任务 1

这些标签基于任务是否有要执行的操作以及 Gradle 是否执行了这些操作。操作包括但不限于编译代码、压缩文件和发布档案。

(no label)或者EXECUTED

任务执行其操作。

  • 任务有动作,Gradle 执行它们。

  • 任务没有操作和一些依赖项,Gradle 执行了一个或多个依赖项。另请参见生命周期任务

UP-TO-DATE

任务的输出没有改变。

  • 任务有输出和输入,但它们没有改变。请参阅增量构建

  • 任务有操作,但任务告诉 Gradle 它没有更改其输出。

  • 任务没有操作和一些依赖关系,但所有依赖关系都是UP-TO-DATE,SKIPPEDFROM-CACHE。请参阅生命周期任务

  • 任务没有操作,也没有依赖性。

FROM-CACHE

任务的输出可以从之前的执行中找到。

  • 任务已从构建缓存中恢复输出。请参阅构建缓存

SKIPPED

任务未执行其操作。

NO-SOURCE

任务不需要执行其操作。

  • 任务有输入和输出,但没有来源(即未找到输入)。

任务组和描述

任务组和描述用于组织和描述任务。

团体

任务组用于对任务进行分类。当您运行时./gradlew tasks,任务会在各自的组下列出,从而更容易理解它们的目的以及与其他任务的关系。组是使用该group属性设置的。

描述

描述提供任务用途的简要说明。当您运行时./gradlew tasks,每个任务旁边都会显示说明,帮助您了解其目的以及如何使用它。描述是使用description属性设置的。

让我们以一个基本的 Java 应用程序为例。该构建包含一个名为 的子项目app

app让我们列出目前可用的任务:

$ ./gradlew :app:tasks

> Task :app:tasks

------------------------------------------------------------
Tasks runnable from project ':app'
------------------------------------------------------------

Application tasks
-----------------
run - Runs this project as a JVM application.

Build tasks
-----------
assemble - Assembles the outputs of this project.

在这里,任务是具有描述的组:run的一部分。在代码中,它看起来像这样:ApplicationRuns this project as a JVM application

app/build.gradle.kts
tasks.register("run") {
    group = "Application"
    description = "Runs this project as a JVM application."
}
app/build.gradle
tasks.register("run") {
    group = "Application"
    description = "Runs this project as a JVM application."
}

私人和隐藏任务

Gradle 不支持将任务标记为private

:tasks但是,只有在task.group设置了该值或者没有其他任务依赖于它时,任务才会在运行时显示。

例如,以下任务在运行时不会出现,./gradlew :app:tasks因为它没有组;它被称为隐藏任务:

app/build.gradle.kts
tasks.register("helloTask") {
    println("Hello")
}
app/build.gradle
tasks.register("helloTask") {
    println("Hello")
}

虽然helloTask没有列出,但仍然可以通过Gradle执行:

$ ./gradlew :app:tasks

> Task :app:tasks

------------------------------------------------------------
Tasks runnable from project ':app'
------------------------------------------------------------

Application tasks
-----------------
run - Runs this project as a JVM application

Build tasks
-----------
assemble - Assembles the outputs of this project.

让我们向同一任务添加一个组:

app/build.gradle.kts
tasks.register("helloTask") {
    group = "Other"
    description = "Hello task"
    println("Hello")
}
app/build.gradle
tasks.register("helloTask") {
    group = "Other"
    description = "Hello task"
    println("Hello")
}

现在组已添加,任务可见:

$ ./gradlew :app:tasks

> Task :app:tasks

------------------------------------------------------------
Tasks runnable from project ':app'
------------------------------------------------------------

Application tasks
-----------------
run - Runs this project as a JVM application

Build tasks
-----------
assemble - Assembles the outputs of this project.

Other tasks
-----------
helloTask - Hello task

反之,./gradlew tasks --all将显示所有任务;列出了隐藏可见的任务。

任务分组

如果您想自定义在列出时向用户显示哪些任务,您可以对任务进行分组并设置每个组的可见性。

请记住,即使您隐藏任务,它们仍然可用,并且 Gradle 仍然可以运行它们。

init让我们从 Gradle为具有多个子项目的 Java 应用程序构建的示例开始。项目结构如下:

gradle-project
├── app
│   ├── build.gradle.kts
│   └── src                 // some java code
│       └── ...
├── utilities
│   ├── build.gradle.kts
│   └── src                 // some java code
│       └── ...
├── list
│   ├── build.gradle.kts
│   └── src                 // some java code
│       └── ...
├── buildSrc
│   ├── build.gradle.kts
│   ├── settings.gradle.kts
│   └── src                 // common build logic
│       └── ...
├── settings.gradle.kts
├── gradle
├── gradlew
└── gradlew.bat
gradle-project
├── app
│   ├── build.gradle
│   └── src             // some java code
│       └── ...
├── utilities
│   ├── build.gradle
│   └── src             // some java code
│       └── ...
├── list
│   ├── build.gradle
│   └── src             // some java code
│       └── ...
├── buildSrc
│   ├── build.gradle
│   ├── settings.gradle
│   └── src             // common build logic
│       └── ...
├── settings.gradle
├── gradle
├── gradlew
└── gradlew.bat

运行app:tasks以查看app子项目中的可用任务:

$ ./gradlew :app:tasks

> Task :app:tasks

------------------------------------------------------------
Tasks runnable from project ':app'
------------------------------------------------------------

Application tasks
-----------------
run - Runs this project as a JVM application

Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
classes - Assembles main classes.
clean - Deletes the build directory.
jar - Assembles a jar archive containing the classes of the 'main' feature.
testClasses - Assembles test classes.

Distribution tasks
------------------
assembleDist - Assembles the main distributions
distTar - Bundles the project as a distribution.
distZip - Bundles the project as a distribution.
installDist - Installs the project as a distribution as-is.

Documentation tasks
-------------------
javadoc - Generates Javadoc API documentation for the 'main' feature.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in project ':app'.
dependencies - Displays all dependencies declared in project ':app'.
dependencyInsight - Displays the insight into a specific dependency in project ':app'.
help - Displays a help message.
javaToolchains - Displays the detected java toolchains.
kotlinDslAccessorsReport - Prints the Kotlin code for accessing the currently available project extensions and conventions.
outgoingVariants - Displays the outgoing variants of project ':app'.
projects - Displays the sub-projects of project ':app'.
properties - Displays the properties of project ':app'.
resolvableConfigurations - Displays the configurations that can be resolved in project ':app'.
tasks - Displays the tasks runnable from project ':app'.

Verification tasks
------------------
check - Runs all checks.
test - Runs the test suite.

如果我们查看可用任务列表,即使对于标准 Java 项目,也会发现它非常广泛。使用构建的开发人员很少直接需要其中许多任务。

我们可以配置:tasks任务并将任务限制为特定组显示。

让我们创建自己的组,以便通过更新构建脚本默认隐藏所有任务app

app/build.gradle.kts
val myBuildGroup = "my app build"               // Create a group name

tasks.register<TaskReportTask>("tasksAll") {    // Register the tasksAll task
    group = myBuildGroup
    description = "Show additional tasks."
    setShowDetail(true)
}

tasks.named<TaskReportTask>("tasks") {          // Move all existing tasks to the group
    displayGroup = myBuildGroup
}
app/build.gradle
def myBuildGroup = "my app build"               // Create a group name

tasks.register(TaskReportTask, "tasksAll") {    // Register the tasksAll task
    group = myBuildGroup
    description = "Show additional tasks."
    setShowDetail(true)
}

tasks.named(TaskReportTask, "tasks") {          // Move all existing tasks to the group
    displayGroup = myBuildGroup
}

现在,当我们列出 中可用的任务时app,列表会更短:

$ ./gradlew :app:tasks

> Task :app:tasks

------------------------------------------------------------
Tasks runnable from project ':app'
------------------------------------------------------------

My app build tasks
------------------
tasksAll - Show additional tasks.

任务类别

Gradle 区分两类任务:

  1. 生命周期任务

  2. 可操作的任务

生命周期任务定义您可以调用的目标,例如:build您的项目。生命周期任务不向 Gradle 提供操作。他们必须连接到可操作的任务。 Gradlebase插件仅添加生命周期任务。

可操作任务定义 Gradle 要执行的操作,例如:compileJava编译项目的 Java 代码。操作包括创建 JAR、压缩文件、发布档案等等。像java-library插件这样的插件添加了可操作的任务。

让我们更新上一个示例的构建脚本,该脚本当前是一个空文件,以便我们的app子项目是一个 Java 库:

app/build.gradle.kts
plugins {
    id("java-library")
}
app/build.gradle
plugins {
    id('java-library')
}

我们再次列出可用的任务,看看有哪些新任务可用:

$ ./gradlew :app:tasks

> Task :app:tasks

------------------------------------------------------------
Tasks runnable from project ':app'
------------------------------------------------------------

Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
classes - Assembles main classes.
clean - Deletes the build directory.
jar - Assembles a jar archive containing the classes of the 'main' feature.
testClasses - Assembles test classes.

Documentation tasks
-------------------
javadoc - Generates Javadoc API documentation for the 'main' feature.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in project ':app'.
dependencies - Displays all dependencies declared in project ':app'.
dependencyInsight - Displays the insight into a specific dependency in project ':app'.
help - Displays a help message.
javaToolchains - Displays the detected java toolchains.
outgoingVariants - Displays the outgoing variants of project ':app'.
projects - Displays the sub-projects of project ':app'.
properties - Displays the properties of project ':app'.
resolvableConfigurations - Displays the configurations that can be resolved in project ':app'.
tasks - Displays the tasks runnable from project ':app'.

Verification tasks
------------------
check - Runs all checks.
test - Runs the test suite.

我们看到有许多新任务可用,例如jartestClasses

此外,该java-library插件还将可操作的任务连接到生命周期任务。如果我们调用该:build任务,我们可以看到包括该任务在内的多个任务已被执行:app:compileJava

$./gradlew :app:build

> Task :app:compileJava
> Task :app:processResources NO-SOURCE
> Task :app:classes
> Task :app:jar
> Task :app:assemble
> Task :app:compileTestJava
> Task :app:processTestResources NO-SOURCE
> Task :app:testClasses
> Task :app:test
> Task :app:check
> Task :app:build

可操作:compileJava任务连接到生命周期:build任务。

增量任务

Gradle 任务的一个关键特征是其增量性质。

Gradle 可以重用之前构建的结果。因此,如果我们之前已经构建了项目并且仅进行了较小的更改,则重新运行:build将不需要 Gradle 执行大量工作。

例如,如果我们只修改项目中的测试代码,而生产代码保持不变,则执行构建只会重新编译测试代码。 Gradle 将生产代码的任务标记为UP-TO-DATE,表示自上次成功构建以来它保持不变:

$./gradlew :app:build

lkassovic@MacBook-Pro temp1 % ./gradlew :app:build
> Task :app:compileJava UP-TO-DATE
> Task :app:processResources NO-SOURCE
> Task :app:classes UP-TO-DATE
> Task :app:jar UP-TO-DATE
> Task :app:assemble UP-TO-DATE
> Task :app:compileTestJava
> Task :app:processTestResources NO-SOURCE
> Task :app:testClasses
> Task :app:test
> Task :app:check UP-TO-DATE
> Task :app:build UP-TO-DATE

缓存任务

Gradle 可以使用构建缓存重用过go构建的结果。

--build-cache 要启用此功能,请使用命令行org.gradle.caching=true参数或在文件中设置来激活构建缓存gradle.properties

此优化有可能显着加速您的构建:

$./gradlew :app:clean :app:build --build-cache

> Task :app:compileJava FROM-CACHE
> Task :app:processResources NO-SOURCE
> Task :app:classes UP-TO-DATE
> Task :app:jar
> Task :app:assemble
> Task :app:compileTestJava FROM-CACHE
> Task :app:processTestResources NO-SOURCE
> Task :app:testClasses UP-TO-DATE
> Task :app:test FROM-CACHE
> Task :app:check UP-TO-DATE
> Task :app:build

当 Gradle 可以从缓存中获取任务的输出时,它会使用 来标记该任务FROM-CACHE

如果您定期在分支之间切换,构建缓存会很方便。 Gradle 支持本地和远程构建缓存。

开发任务

开发 Gradle 任务时,您有两种选择:

  1. 使用现有的 Gradle 任务类型,例如ZipCopyDelete

  2. 创建您自己的 Gradle 任务类型,例如MyResolveTaskCustomTaskUsingToolchains

任务类型只是 GradleTask类的子类。

对于 Gradle 任务,需要考虑三种状态:

  1. 注册任务 - 在构建逻辑中使用任务(由您实现或由 Gradle 提供)。

  2. 配置任务 - 定义已注册任务的输入和输出。

  3. 实现任务 - 创建自定义任务类(即自定义类类型)。

注册通常是用该register()方法完成的。
配置任务通常使用该named()方法完成。
实现任务通常是通过扩展 Gradle 的DefaultTask类来完成的:

tasks.register<Copy>("myCopy")                              (1)

tasks.named<Copy>("myCopy") {                               (2)
    from("resources")
    into("target")
    include("**/*.txt", "**/*.xml", "**/*.properties")
}

abstract class MyCopyTask : DefaultTask() {                 (3)
    @TaskAction
    fun copyFiles() {
        val sourceDir = File("sourceDir")
        val destinationDir = File("destinationDir")
        sourceDir.listFiles()?.forEach { file ->
            if (file.isFile && file.extension == "txt") {
                file.copyTo(File(destinationDir, file.name))
            }
        }
    }
}
1 Register the myCopy task of type Copy to let Gradle know we intend to use it in our build logic.
2 Configure the registered myCopy task with the inputs and outputs it needs according to its API.
3 Implement a custom task type called MyCopyTask which extends DefaultTask and defines the copyFiles task action.
tasks.register(Copy, "myCopy")                              (1)

tasks.named(Copy, "myCopy") {                               (2)
    from "resources"
    into "target"
    include "**/*.txt", "**/*.xml", "**/*.properties"
}

abstract class MyCopyTask extends DefaultTask {             (3)
    @TaskAction
    void copyFiles() {
        fileTree('sourceDir').matching {
            include '**/*.txt'
        }.forEach { file ->
            file.copyTo(file.path.replace('sourceDir', 'destinationDir'))
        }
    }
}
1 Register the myCopy task of type Copy to let Gradle know we intend to use it in our build logic.
2 Configure the registered myCopy task with the inputs and outputs it needs according to its API.
3 Implement a custom task type called MyCopyTask which extends DefaultTask and defines the copyFiles task action.

1. 注册任务

您可以通过在构建脚本或插件中注册任务来定义 Gradle 要执行的操作。

任务是使用任务名称字符串定义的:

build.gradle.kts
tasks.register("hello") {
    doLast {
        println("hello")
    }
}
build.gradle
tasks.register('hello') {
    doLast {
        println 'hello'
    }
}

在上面的示例中,任务被添加到TasksCollectionusingregister()中的方法中TaskContainer

2. 配置任务

必须配置 Gradle 任务才能成功完成其操作。如果任务需要压缩文件,则必须配置文件名和位置。您可以参考Gradle 任务的APIZip以了解如何正确配置它。

我们Copy以 Gradle 提供的任务为例。我们首先在构建脚本中注册一个名为myCopyof 类型的任务:Copy

build.gradle.kts
tasks.register<Copy>("myCopy")
build.gradle
tasks.register('myCopy', Copy)

这会注册一个没有默认行为的复制任务。由于任务的类型是CopyGradle 支持的任务类型,因此可以使用其API进行配置。

以下示例展示了实现相同配置的几种方法:

1、使用named()方法:

用于named()配置在其他地方注册的现有任务:

build.gradle.kts
tasks.named<Copy>("myCopy") {
    from("resources")
    into("target")
    include("**/*.txt", "**/*.xml", "**/*.properties")
}
build.gradle
tasks.named('myCopy') {
    from 'resources'
    into 'target'
    include('**/*.txt', '**/*.xml', '**/*.properties')
}

2. 使用配置块:

注册任务后立即使用块来配置任务:

build.gradle.kts
tasks.register<Copy>("copy") {
   from("resources")
   into("target")
   include("**/*.txt", "**/*.xml", "**/*.properties")
}
build.gradle
tasks.register('copy', Copy) {
   from 'resources'
   into 'target'
   include('**/*.txt', '**/*.xml', '**/*.properties')
}

3. 将方法命名为 call:

仅 Groovy 支持的一个流行选项是速记符号:

copy {
    from("resources")
    into("target")
    include("**/*.txt", "**/*.xml", "**/*.properties")
}
此选项会破坏任务配置避免,因此不推荐!

无论选择哪种方法,任务都会配置要复制的文件的名称和文件的位置。

三、落实任务

Gradle 提供了许多任务类型,包括DeleteJavadocCopyExecTarPmd。如果 Gradle 没有提供满足您的构建逻辑需求的任务类型,您可以实现自定义任务类型。

要创建自定义任务类,您需要扩展DefaultTask并使扩展类抽象:

app/build.gradle.kts
abstract class MyCopyTask extends DefaultTask {

}
app/build.gradle
abstract class MyCopyTask : DefaultTask() {

}

您可以在实现任务中了解有关开发自定义任务类型的更多信息。