Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create gradle task which always runs?

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. :)

like image 795
CasualT Avatar asked Jan 09 '14 19:01

CasualT


People also ask

How do I run a default task in Gradle?

Gradle allows you to define one or more default tasks that are executed if no other tasks are specified. defaultTasks 'clean', 'run' tasks. register('clean') { doLast { println 'Default Cleaning! ' } } tasks.

Does Gradle build run all tasks?

Gradle can handle the build file using gradle command. This command will compile each task in such an order that they are listed and execute each task along with the dependencies using different options.

What is a lifecycle task in Gradle?

In Gradle terms this means that you can define tasks and dependencies between tasks. Gradle guarantees that these tasks are executed in the order of their dependencies, and that each task is executed only once. These tasks form a Directed Acyclic Graph.


1 Answers

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
  }
}
like image 118
akhikhl Avatar answered Sep 20 '22 07:09

akhikhl