简书链接:gradle任务笔记
文章字数:178,阅读全文大约需要1分钟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
open class GreetingTask : DefaultTask() {
var greeting = "hello from GreetingTask"

@TaskAction
fun greet() {
println(greeting)
}
}

// Use the default greeting
task<GreetingTask>("hello")

// Customize the greeting
task<GreetingTask>("greeting") {
greeting = "greetings from GreetingTask"
}

执行gradle --quiet hello greeting
结果

1
2
hello from GreetingTask
greetings from GreetingTask

结论 一个是修改了,一个是没修改,执行会默认调用@TaskAction里面的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// tag::all[]
// tag::task[]
class GreetingToFileTask extends DefaultTask {

def destination

File getDestination() {
project.file(destination)
}

@TaskAction
def greet() {
def file = getDestination()
file.parentFile.mkdirs()
file.write 'Hello!'
}
}
// end::task[]

// tag::config[]
task greet(type: GreetingToFileTask) {
destination = { project.greetingFile }
}

task sayGreeting(dependsOn: greet) {
doLast {
println file(greetingFile).text
}
}

ext.greetingFile = "$buildDir/hello.txt"

执行gradle --quiet sayGreeting
结论, 先执行 任务 greet,而这个任务会执行写入hello到hello.txt 然后sayGreeting执行就把写入的文本打印出来。

任务的变量写法

1
2
3
4
5
6
7
task myCopy(type: Copy)

// tag::configure[]
Copy myCopy = tasks.getByName("myCopy")
myCopy.from 'resources'
myCopy.into 'target'
myCopy.include('**/*.txt', '**/*.xml', '**/*.properties')

或者

1
2
3
4
5
6
7
8
9
10
task myCopy(type: Copy)
// end::declare-task[]

// tag::configure[]
// Configure task using Groovy dynamic task configuration block
myCopy {
from 'resources'
into 'target'
}
myCopy.include('**/*.txt', '**/*.xml', '**/*.properties')

或者

1
2
3
4
5
6
7
8
task copy(type: Copy) {
// end::no-description[]
description 'Copies the resource directory to the target directory.'
// tag::no-description[]
from 'resources'
into 'target'
include('**/*.txt', '**/*.xml', '**/*.properties')
}

都是一个意思,是代表从这个目录复制指定后缀的到某个目录。

finalizedBy

1
2
3
4
5
6
7
8
9
10
11
12
task taskX {
doLast {
println 'taskX'
}
}
task taskY {
doLast {
println 'taskY'
}
}

taskX.finalizedBy taskY

表示不管成功或者失败都会在taskX执行完毕之后执行taskY,

kotlin通过代理创建任务

1
2
3
4
5
6
7
8
9
10
11
val hello by tasks.creating {
doLast {
println("hello")
}
}

val copy by tasks.creating(Copy::class) {
from(file("srcDir"))
into(buildDir)
}

groovy的任务定义方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
task(hello) {
doLast {
println "hello"
}
}

task(copy, type: Copy) {
from(file('src'))
into(buildDir)
}

task copy1(type: Copy) {
//// end::no-description[]
// description 'Copies the resource directory to the target directory.'
//// tag::no-description[]
// from 'resources'
// into 'target'
// include('**/*.txt', '**/*.xml', '**/*.properties')
}

这里分别代表创建了task hello和task copy