How to create gradle task which always runs?

2019-03-25 10:09发布

I'm likely overlooking something pretty core/obvious, but how can I create a task that will always be executed for every task/target?

I can do something like:

task someTask << {
    println "I sometimes run"
}
println "I always run"

But it would be much more desirable to have the always running part in a task.

The closest I've come is:

task someTask << {
    println "I sometimes run"
}

println "I always run"

void helloThing() {
    println "I always run too. Hello?"
}

helloThing()

So, using a method is an 'ok' solution, but I was hoping there'd be a way to specifically designate/re-use a task.

Hopefully somebody has a way to do this. :)

3条回答
Lonely孤独者°
2楼-- · 2019-03-25 10:57

Assuming the goal is to print system information, you could either just always print the information in the configuration phase (outside a task declaration), and have a dummy task systemStatus that does nothing (because the information is printed anyway). Or you could implement it as a regular task, and make sure the task always gets run by adding ":systemStatus" as the first item of gradle.startParameter.taskNames (a list of strings), which simulates someone always typing gradle :systemStatus .... Or you could leverage a hook such as gradle.projectsLoaded { ... } to print the information there.

查看更多
爷的心禁止访问
3楼-- · 2019-03-25 11:00

This attaches a closure to every task in every project in the given build:

def someClosure = { task ->
  println "task executed: $task"
}

allprojects {
  afterEvaluate {
    for(def task in it.tasks)
      task << someClosure
  }
}

If you need the function/closure to be called only once per build, before all tasks of all projects, use this:

task('MyTask') << {
  println 'Pre-build hook!'
}

allprojects {
  afterEvaluate {
    for(def task in it.tasks)
      if(task != rootProject.tasks.MyTask)
        task.dependsOn rootProject.tasks.MyTask
  }
}

If you need the function/closure to be called only once per build, after all tasks of all projects, use this:

task('MyTask') << {
  println 'Post-build hook!'
}

allprojects {
  afterEvaluate {
    for(def task in it.tasks)
      if(task != rootProject.tasks.MyTask)
        task.finalizedBy rootProject.tasks.MyTask
  }
}
查看更多
我想做一个坏孩纸
4楼-- · 2019-03-25 11:07

What's wrong with invoking it straight from the root build.gradle?

task init << {
    println "I always run"
}

tasks.init.execute()
查看更多
登录 后发表回答