创建一个使用参数执行另一个任务的任务

时间:2015-12-01 12:50:39

标签: android gradle android-gradle build.gradle

如何使用参数创建执行其他任务的任务?

taskB将从命令行接收参数(这里它被硬编码为val1和val2)并且我想将这些参数传递给其他任务 - 例如taskA和taskC,并定义它们将被执行的顺序。

这是我尝试过的,它不起作用

task taskB(){
    def val1 = '1'
    def val2 = 'abc'

    dependsOn "taskA -PparamA=$val1 -PparamB=$val2",
              "taskC -PparamA=$val1 -PparamB=$val2"

    taskC.mustRunAfter taskA
}

1 个答案:

答案 0 :(得分:0)

你可以这样做:

task taskA() << {
    //properties are printed during the execution phase
    println paramA
    println paramB
}

task taskC() << {
    //properties are printed during the execution phase
    println paramA
    println paramB
}

task taskB(){
    def val1 = '1'
    def val2 = 'abc'

    //here you set task properties
    taskA.ext.paramA=val1
    taskA.ext.paramB=val2

    //here you set task properties
    taskC.ext.paramA=val1
    taskC.ext.paramB=val2

    //provide task depoendencies
    dependsOn taskA, taskC
    //and tasks order
    taskC.mustRunAfter taskA
}

在这种情况下,ext表示此属性不是全局属性,但仅由任务本身拥有。

上述示例的问题在于taskB传播的值仅在执行阶段taskAtaskC中可用。如果在配置期间需要它们,可以将它们作为项目属性传递,例如:

task taskB(){
    def val1 = '1'
    def val2 = 'abc'

    //here you set project properties
    project.ext.paramA=val1
    project.ext.paramB=val2
}

task taskA() {
    //properties are printed during the configuration phase
    println project.ext.paramA
    println project.ext.paramB
}

task taskC() << {
    //properties are printed during the execution phase
    println project.ext.paramA
    println project.ext.paramB
}

//provide task depoendencies
taskB.dependsOn taskA, taskC
//and tasks order
taskC.mustRunAfter taskA