Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 36 ยท Projects and Tasks

Gradle Tasks: Registering, doFirst, doLast and onlyIf

Create Gradle tasks with tasks.register, add actions with doFirst and doLast, group and describe them, skip them with onlyIf, and configure existing tasks.

A task is the unit of work in Gradle: compile code, copy files, run tests, create a zip. Plugins add many tasks for you, but you will constantly write your own small ones: print a version, generate a file, call a script. This lesson covers how to register a task, how its actions run, how to describe and group it so it shows up nicely in ./gradlew tasks, and how to make it conditional.

Gradle code is read-only here; runnable Java stand-ins model the action list so you can see how doFirst and doLast interact.

Registering a task

The modern way is tasks.register. It creates a lazy task: Gradle records the registration, but only creates and configures the task if something needs it (see lazy configuration).

Kotlin
// build.gradle.kts
tasks.register("hello") {
    group = "demo"
    description = "Prints a greeting"
    doLast {
        println("Hello from ${project.name}")
    }
}

Run it:

Terminal
./gradlew hello
TEXT
> Task :hello
Hello from shop

The same task in Groovy:

GROOVY
tasks.register('hello') {
    group = 'demo'
    description = 'Prints a greeting'
    doLast {
        println "Hello from ${project.name}"
    }
}

group and description are what ./gradlew tasks shows; a task without a group appears only under tasks --all. Older builds use task hello { } or tasks.create; those create the task eagerly every time the script is evaluated. Prefer register.

Actions: doFirst and doLast

A task owns an ordered list of actions. doLast appends to the end; doFirst inserts at the beginning. Because tasks often get actions from several places (a plugin, your script), the final order can surprise you.

Kotlin
tasks.register("report") {
    doLast  { println("2: written by the script") }
    doFirst { println("1: runs before everything else") }
    doLast  { println("3: another last action") }
}
TEXT
> Task :report
1: runs before everything else
2: written by the script
3: another last action

doFirst blocks run in reverse order of addition (the newest one runs first); doLast blocks run in order of addition. This matters when you extend an existing task such as jar or test.

Stand-in: action ordering

The stand-in below is not Gradle. It models a task as an action list with doFirst and doLast, so you can predict the order.

Java Stand-in: doFirst and doLast order

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.

Check your prediction: D, B, A, C. The later doFirst runs earliest.

Conditional tasks: onlyIf and enabled

A task can decide at execution time whether to run:

Kotlin
tasks.register("deploy") {
    onlyIf { System.getenv("CI") != null }
    doLast { println("Deploying...") }
}

When the predicate returns false the task is marked SKIPPED. enabled = false disables the task entirely:

Kotlin
tasks.named("javadoc") { enabled = false }

To stop the build with a clear message, throw a GradleException:

Kotlin
tasks.register("checkEnv") {
    doLast {
        if (System.getenv("API_KEY") == null) {
            throw GradleException("API_KEY is not set")
        }
    }
}

To skip a task softly from inside its action, throw StopExecutionException; the build continues with the next task.

Stand-in: onlyIf

Java Stand-in: a task with a predicate

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.

Configuring tasks that already exist

You rarely create every task yourself. More often you tweak a task that a plugin provided. Look it up lazily with named:

Kotlin
tasks.named<Test>("test") {
    useJUnitPlatform()
    maxHeapSize = "1g"
}

tasks.named<Jar>("jar") {
    archiveBaseName = "shop-api"
}

To change every task of a type use withType:

Kotlin
tasks.withType<JavaCompile>().configureEach {
    options.encoding = "UTF-8"
    options.compilerArgs.add("-Xlint:all")
}

configureEach applies lazily, as each task is created, so it does not force configuration of tasks nobody needs.

Grouping, naming and good habits

  • Choose lowercase camelCase names: generateDocs, not Generate_Docs.
  • Always set group and description for tasks you expect people to run.
  • Keep task configuration (property assignments) in the configure block and work in doFirst/doLast or a typed task class, as you learned in the lifecycle lesson.
  • Do not call project.exec or read files at configuration time.
  • Print with logger.lifecycle("...") or logger.info("...") instead of println when you want log levels.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is tasks.register preferred over tasks.create?

    Lazy registration avoids configuring tasks that are never executed, which keeps configuration time low.
  2. 2. A task has doLast A, then doFirst B, then doLast C. In which order do the actions run?

    doFirst inserts at the front and doLast appends, so the order is B, A, C.
  3. 3. What does a task show when its onlyIf predicate returns false?

    A false predicate skips the task, which Gradle reports as SKIPPED.
  4. 4. Which two properties make a task appear nicely in ./gradlew tasks?

    Tasks with a group are listed under that group, together with their description.

Summary

  • A task is a unit of work with an ordered list of actions.
  • Use tasks.register("name") { ... } and set group and description.
  • doFirst inserts at the front, doLast appends; use them for work, not for configuration.
  • onlyIf and enabled control whether a task runs; GradleException fails the build with a message.
  • Configure existing tasks with tasks.named and tasks.withType(...).configureEach.

Next: Task Dependencies and Ordering