2

This question is for gradle (>= 2.4). I would like to write a custom task like the following:

https://docs.gradle.org/current/userguide/custom_tasks.html

class GreetingTask extends DefaultTask {
    @TaskAction
    def greet() {
        println 'hello from GreetingTask'
    }
}

task hello(type: GreetingTask)

how can I make this task run during execution phase? Is passing an empty closure with

<< {

}

the only solution?

Edit

the task is supposed to be used in a multiproject build with several tasks as dependencies.

I'd like that the command gradle build would build all the projects by saying something like

`build.dependsOn(hello)`

but seems that the task hello is called during configuration phase of the build.

14
  • That is what it looks like to me, but I don't know much about this. Jul 13, 2015 at 18:47
  • Without the closure, what happens when you execute gradle hello ?
    – jaco0646
    Jul 13, 2015 at 18:50
  • @jaco0646 you are calling the task directly. I need it to be called during execution phase and not configuration phase
    – iggy
    Jul 13, 2015 at 18:56
  • 1
    @iggy why do you think the task is executed during configuration phase? Jul 13, 2015 at 22:06
  • 1
    @iggy your question contains a link explaining that mechanism. It says: Gradle will call the method when the task executes. Note the wording. It says "when the task executes". Not "when the task is configured". So the method annotated with @TaskAction is what the task does, during the execution phase. It also says: You don't have to use a method to define the behaviour for the task. You could, for instance, call doFirst() or doLast() with a closure in the task constructor to add behaviour. So this TaskAction-based mechanism is just another way of telling the task what to do when executed
    – JB Nizet
    Jul 14, 2015 at 7:14

1 Answer 1

5

Add the following to a build.gradle file:

class GreetingTask extends DefaultTask {
    @TaskAction
    def greet() {
        println 'hello from GreetingTask'
    }
}

task hello(type: GreetingTask) {
    println "This is the configuration phase"

    doFirst {
        println "This is the execution phase"
    }
}

Now execute gradle hello. The output you will see is

This is the configuration phase
:hello
This is the execution phase
hello from GreetingTask

BUILD SUCCESSFUL

As you can see, the output from the task occurs after the doFirst(), which definitely happens during the execution phase.

1
  • thanks for explaining, I had some gaps in understanding how configuration phase in gradle works
    – iggy
    Jul 17, 2015 at 8:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.