Gradle Cheat Sheet (4): Task Dependencies
1. dependsOn
任务A dependsOn 任务B,表示任务A只能在任务B完成之后进行。例如:
task putOnSocks { doLast { println "Putting on Socks." } } task putOnShoes { dependsOn "putOnSocks" doLast { println "Putting on Shoes." } }
执行:
$ gradle putOnShoes
输出为:
:putOnSocks Putting on Socks. :putOnShoes Putting on Shoes.
此时使用gradle tasks 会发现看不到putOnSocks这个任务,因为Gradle认为putOnSocks只是为了帮助putOnShoes而存在的。可以通过:
$ gradle tasks --all
查看所有任务,就可以看到putOnSocks了。
2. finalizedBy
任务A finalizedBy 任务B,表示每次任务A执行完成后,都要再接着执行任务B。例如:
task eatBreakfast { finalizedBy "brushYourTeeth" doLast{ println "Om nom nom breakfast!" } } task brushYourTeeth { doLast { println "Brushie Brushie Brushie." } }
执行:
$ gradle eatBreakfast
输出为:
:eatBreakfast Om nom nom breakfast! :brushYourTeeth Brushie Brushie Brushie.
3. mustRunAfter
任务A mustRunAfter 任务B,表示如果要同时执行任务A和任务B,则先执行任务B,任务B完成后再执行任务A。任务A和任务B之间没有其他依赖,都可以单独执行。例如:
task takeShower { doLast { println "Taking a shower." } } task putOnFragrance { shouldRunAfter "takeShower" doLast{ println "Smellin' fresh!" } }
执行:
$ gradle putOnFragrance takeShower
输出为:
:takeShower Taking a shower. :putOnFragrance Smellin' fresh!
4. 多依赖
一个任务可以依赖于多个任务:
task getReady { // Remember that when assigning a collection to a property, we need the // equals sign dependsOn = ["takeShower", "eatBreakfast", "putOnShoes"] }
注意这里把集合赋给dependsOn,不能省略等号。执行:
$ gradle getReady
输出为:
:eatBreakfast Om nom nom breakfast! :brushYourTeeth Brushie Brushie Brushie. :putOnSocks Putting on Socks. :putOnShoes Putting on Shoes. :takeShower Taking a shower. :getReady
从上面的输出可以发现一个问题,takeShower被放在了putOnSocks和putOnShoes之后,因为takeShower和putOnSocks、putOnShoes之间都没有依赖,需要再加上一条依赖:
putOnShoes.mustRunAfter takeShower
此时再执行:
$ gradle getReady
输出为:
:eatBreakfast Om nom nom breakfast! :brushYourTeeth Brushie Brushie Brushie. :takeShower Taking a shower. :putOnSocks Putting on Socks. :putOnShoes Putting on Shoes. :getReady
可见takeShower放在了putOnSocks之前(putOnShoes依赖于putOnSocks)。
5. 匹配任务
可以使用tasks.matching在当前的任务中进行匹配,查找特定的任务。如为getEquipped添加dependsOn依赖,为所有以“putOn”开头的任务:
task getEquipped { dependsOn tasks.matching{ task -> task.name.startsWith("putOn")} doLast { println "All geared up!" } }
执行:
$ gradle getEquipped
输出为:
:putOnFragrance Smellin' fresh! :putOnSocks Putting on Socks. :putOnShoes Putting on Shoes. :getEquipped All geared up!
本部分的完整代码可以在这里找到。