Call tasks a few times with different condition


(Viktor) #1

Hi all!
I tried to call task from another different tasks using ‘dependsOn’ a few times with different conditions.

Example:

gradle.properies
group=a,b,c

gradle.build
def array=group.split(’,’)
def var
task A{
doLast{
println “taskA=”+var
}
}
task B{
doLast{
println “taskB=”+var
}
}
task C{
doLast{
println “taskC=”+var
}
}
array.eachWithIndex { letter, index ->
task “newTask${index}” {
if (letter==‘a’) {
var = letter
dependsOn A
dependsOn B
} else {
if(letter==‘b’){
var = letter
dependsOn A
dependsOn C
} else {
if(letter==‘c’){
var = letter
dependsOn B
dependsOn C
}
}
}
}

newTask2.dependsOn newTask1
newTask1.dependsOn newTask0

I would to get in result
:newTask0
Task A=a
Task B=a

:newTask1
Task A=b
Task B=b

:newTask2
Task A=c
Task B=c

Please, tell me how I can realize my idea.
Thank you


(James Justinic) #2

You cannot have the same task run multiple times in the same build. Instead of creating ad-hoc tasks for A, B, and C , you should create custom task types for the work done by A, B, and C. You will then create multiple tasks of this type, configured with the correct variable. See Gradle Guide on Writing Gradle Tasks.

Your A task could look something like this:

class TaskA extends DefaultTask {
    String var

    @TaskAction
    void taskAction() {
        println "taskA=${var}"
    }
}

Your logic would then decide which two task types to create for each letter, set the var to that letter, and then add any task dependencies that you want.


(Dimitar Dimitrov) #3

Agree about the task-per-invocation. If the tasks are similar enough, you may consider using a task rules and ad-hoc task (rather than implementing full fledged custom task - see the example in the link).


(Viktor) #4

Thank you for your response!


(Viktor) #5

Thank you for your response!) It’s may to work correctly, but solution above is easier for using to my project.