Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 36 ยท Projects and Tasks

Custom Task Types: Copy, Exec, Zip and Your Own Classes

Use built-in task types such as Copy, Exec, Zip and Delete, then write your own reusable Gradle task class with typed properties and a @TaskAction method.

A task you define with just doLast { } is an "ad hoc" task. It is quick, but the logic cannot be reused and Gradle cannot tell what it does. A task type is a class that packages logic and declares its inputs and outputs. Gradle ships with many (Copy, Delete, Zip, Exec, Test, JavaCompile), and you can write your own. This lesson shows the built-in ones you will use daily and how to build a small custom type.

Gradle code is read-only here; the stand-ins imitate the class-plus-configuration pattern in Java.

Using built-in task types

You choose the type with the generic argument in Kotlin or type: in Groovy.

Kotlin
tasks.register<Copy>("copyDocs") {
    from("src/docs")
    into(layout.buildDirectory.dir("site"))
    include("**/*.md")
    rename { it.replace(".md", ".txt") }
}

tasks.register<Zip>("zipDocs") {
    from("src/docs")
    archiveFileName = "docs.zip"
    destinationDirectory = layout.buildDirectory.dir("dist")
}

tasks.register<Delete>("cleanTmp") {
    delete(layout.buildDirectory.dir("tmp"))
}

tasks.register<Exec>("gitVersion") {
    commandLine("git", "describe", "--tags", "--always")
    isIgnoreExitValue = true
}

The same copyDocs task in Groovy:

GROOVY
tasks.register('copyDocs', Copy) {
    from 'src/docs'
    into layout.buildDirectory.dir('site')
    include '**/*.md'
}

Notes:

  • Copy and Zip declare their inputs and outputs automatically, so repeated runs are UP-TO-DATE.
  • Exec runs a process. Treat it carefully: it depends on the operating system and PATH, and a plain Exec task has no declared inputs, so declare them if you want caching.
  • JavaExec is the Java-specific cousin: it takes classpath and mainClass. The application plugin's run task is a JavaExec.

Writing your own task class

A custom task is a class extending DefaultTask. Properties use Gradle's managed property types (Property<T>, RegularFileProperty, ...), which are lazy and carry input/output annotations. One method, annotated with @TaskAction, does the work.

Kotlin
// build.gradle.kts (or buildSrc / a plugin)
abstract class Greet : DefaultTask() {

    @get:Input
    abstract val greeting: Property<String>

    @get:Input
    @get:Optional
    abstract val names: ListProperty<String>

    @get:OutputFile
    abstract val outputFile: RegularFileProperty

    @TaskAction
    fun greet() {
        val lines = names.getOrElse(listOf("world")).map { "${greeting.get()}, $it!" }
        outputFile.get().asFile.writeText(lines.joinToString("\n"))
        logger.lifecycle("Wrote ${lines.size} greetings")
    }
}

tasks.register<Greet>("greetTeam") {
    greeting = "Hello"
    names = listOf("Ana", "Ben")
    outputFile = layout.buildDirectory.file("greetings.txt")
}

tasks.register<Greet>("greetWorld") {
    greeting = "Hi"
    outputFile = layout.buildDirectory.file("hi.txt")
}

Why abstract? Gradle generates the property implementations at runtime (they are "managed"), so you declare them as abstract getters. You get lazy evaluation and automatic input fingerprinting for free.

Rules for a good task class

  • Make properties Property<T> (or ListProperty, MapProperty, DirectoryProperty), not plain var.
  • Annotate every property with an input or output annotation, or @Internal.
  • Do work only in the @TaskAction method. Never touch project there: the Project object is not cache- or configuration-cache-friendly. Take values as properties instead.
  • Keep outputs deterministic so the task can be cached with @CacheableTask.

Stand-in: a typed task and two registrations

This program is not Gradle, but it mirrors the structure: one class with typed properties and an action, registered twice with different settings.

Java Stand-in: one task class, two configurations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Stand-in: a Copy-like task with a filter

The real Copy task filters and renames while copying. This stand-in does the same on an in-memory file map, using a glob-like suffix match.

Java Stand-in: from / include / rename / into

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Where to put custom task classes

  1. In build.gradle.kts: fine for a one-off task in one project.
  2. In buildSrc/src/main/kotlin: shared by all projects in the build, recompiled automatically.
  3. In an included build or a published plugin: reusable across repositories (see the Plugins chapter).

Declaring @CacheableTask on the class and @PathSensitive/@Classpath on inputs allows the build cache to reuse results; add it only when the task is deterministic.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which annotation marks the method that does a custom task's work?

    @TaskAction tells Gradle which method to call when the task executes.
  2. 2. Why are custom task properties declared as Property<T> and abstract?

    Managed properties are lazy and are fingerprinted automatically as inputs or outputs.
  3. 3. Which built-in task type creates an archive from files?

    Zip (and its siblings Jar, Tar) package files into an archive.
  4. 4. What should a @TaskAction method avoid using?

    Using project at execution time breaks caching and the configuration cache. Pass values in as properties.

Summary

  • Built-in types (Copy, Zip, Delete, Exec, JavaExec) cover common jobs and declare inputs and outputs for you.
  • A custom task extends DefaultTask, uses managed Property types and has one @TaskAction method.
  • Annotate every property (@Input, @OutputFile, @Internal) so up-to-date checks work.
  • Avoid project inside the action; configure through properties.
  • Put shared task classes in buildSrc or a plugin.

Next: Groovy DSL Basics