How to create gradle task which always runs?

北城余情 提交于 2019-12-03 11:23:15

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.

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
  }
}

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

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

tasks.init.execute()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!