1.查找任务的方式
task hello7{
}
tasks["hello7"].doLast{
//通过名称查找任务,find和get的区别:如果find没有找到,就会返回null,而get会报异常
println tasks.findByName("hello7")
println tasks.getByName("hello7")
//通过路径查找任务,find和get的区别:如果find没有找到,就会返回null,而get会报异常
println tasks.findByPath(":hello7")
println tasks.getByPath(":hello7")
}
可以通过下面进行使用配置task中的属性
task hello8{
}
tasks.findByName("hello8").doLast{
println "啦啦"
}
2.对任务进行分组,这样方便对任务进行分类整理。
task hello9{
group BasePlugin.BUILD_GROUP
description "这个是分组后任务"
doLast{
println "恩恩"
}
}
使用gradle tasks --all命令打印分组后的结果。
3.执行任务顺序
当我们执行Task的时候,其实就是执行其拥有的actions列表,这个列表保存在Task对象实例中的actions成员变量中
使用@TaskAction注解标注,意思是该方法就是Task本身要执行的方法。这是把该action添加到actions list中。
class CustomTask extends DefaultTask{
@TaskAction
def doSelf(){
println "doSelf自身调用"
}
}
//type 相当于继承,表示基于一个存在的Task来创建。
def Task mTask=task mTask(type:CustomTask)
mTask.doFirst{
println "doFirst"
}
mTask.doLast{
println "doLast"
}
4.任务排序
使用shouldRunAfter 和mustRunAfter这两个方法,用来控制任务应该在一个任务之后执行。
task hello10{
doLast{
println "恩恩"
}
}
task hello11{
doLast{
println "噢噢"
}
}
//hello10.shouldRunAfter(hello11)
hello10.mustRunAfter(hello11)
使用gradle hello11 hello10 会发现hello10先执行。
5.任务的启用和禁用
Task中有个enabled属性,用于启用和禁止任务,默认为true.可以设置false,这样执行该task的时候就会跳过。
6.任务断言
断言是一个表达式,Task有一个onlyIf方法,接受一个闭包作为参数。如果闭包返回ture,就执行任务,否则跳过。
但是经过测试,不起作用。执行代码使用 gradle :build //后面的:build表示文件的位置。
task hello12 {
doFirst{
println 'hello world1111'
}
doLast{
println 'hello world2222'
}
}
//使用断言,当返回false的时候,就会跳过hello12方法
hello12.onlyIf {
println '111'
return true
}
7.添加任务规则 会监听所有的任务的执行情况,如果没有这个task那么就会触发这个规则
tasks.addRule("对规则的描述"){String taskName ->
task(taskName){
println "该${taskName}不存在"
}
}