Gradle Task入门演示二

Gradle Task入门演示二

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

Defining tasks

有多种方式可以定义task,现在再来看下面这几种方式,

task(helloTask) << {
    println "hello"
}

task的名字helloTask,还可以使用引号,

task('helloTask2') << {
    println "hello"
}

还可以使用tasks.create 定义一个task。

tasks.create(name: 'helloTask3') << {
    println 'hello'
}


Locating tasks

定位task

task printTaskPath << {
    println tasks.getByPath('hello').path
    println tasks.getByPath(':hello').path
}

执行task输出,

:hello

:hello


Configuring tasks

配置task。如下声明和定义类型为Copy的task,同时定义myCopy的属性。

Copy myCopy = task(myCopy, type: Copy)
myCopy.from 'resources'
myCopy.into 'target'
myCopy.include('**/*.txt', '**/*.xml', '**/*.properties')

上面这种方式时最平常的方式来定义属性,另外一种方式,这种方式使用闭包。

task myCopy(type: Copy)

myCopy {
   from 'resources'
   into 'target'
   include('**/*.txt', '**/*.xml', '**/*.properties')
}

还有如下方式使用闭包定义属性,

task copy(type: Copy) {
   from 'resources'
   into 'target'
   include('**/*.txt', '**/*.xml', '**/*.properties')
}


Order task with mustRunAfter

使用mustRunAfter来定义task的执行顺序,如下,

task pre << {
    println 'pre'
}

task after << {
    println 'after'
}

after.mustRunAfter pre

执行task,

➜  Gradle-Showcase  gradle -q after pre
pre
after

可以看到task是按照 mustRunAfter定义的顺序执行的。


Overwriting a task

当定义相同名称的task时,可以使用overwrite重写前一个task。

task copy(type: Copy)

task copy(overwrite: true) << {
    println('I am the new one.')
}


Adding dependency using closure

如下所示使用闭包声明和定义task的依赖

task taskXXX << {
    println 'taskX'
}

taskXXX.dependsOn {
    tasks.findAll { task -> task.name.startsWith('lib') }
}

task lib1 << {
    println 'lib1'
}

task lib2 << {
    println 'lib2'
}

task notALib << {
    println 'notALib'
}

执行task,

➜  Gradle-Showcase  gradle -q taskXXX
lib1
lib2
taskX


skip task Using StopExecutionException

task执行过程中,可以抛出StopExecutionException异常,中断task的运行

task compile << {
    println 'We are doing the compile.'
}

compile.doFirst {
    // Here you would put arbitrary conditions in real life.
    // But this is used in an integration test so we want defined behavior.
    if (true) {
        throw new StopExecutionException()
    }
}
task myTaskX(dependsOn: 'compile') << {
    println 'I am not affected'
}

执行task,

➜  Gradle-Showcase  gradle -q mytaskX
I am not affected

抛出异常,直接中断了task的处理。


skip task using onlyIf method

如下onlyIf的使用方法,

task helloX << {
    println 'hello world'
}

helloX.onlyIf { !project.hasProperty('skipHello') }


skip task using enable and disable

task disableMe << {
    println 'This should not be printed if the task is disabled.'
}
disableMe.enabled = false

当设置了enabled属性为false的时候,这个task就不会运行。

=====END=====

你可能感兴趣的:(Gradle Task入门演示二)