是否可以在gradle中使用以下内容
task enableMe() << {
println "Enable"
}
task disableMe() << {
shouldRunAfter 'taskAwork'
println "Disable"
}
task taskAwork(){
shouldRunAfter 'enableMe'
println "do work in A while disabled"
}
task taskA(dependsOn: disableMe, taskAwork, enableMe){
}
task taskBwork(){
shouldRunAfter 'enableMe'
println "do work in B while disabled"
}
task taskB(dependsOn: disableMe, taskBwork, enableMe){
}
task taskC(dependsOn: taskA, taskB){
}
因此,当它运行时,任务按顺序执行
disableMe
taskAwork
enableMe
disableMe
taskBwork
enableMe
但是目前,disableMe和enableMe只运行一次..无论如何都设置状态,以便它们可以再次运行。
我能想到的唯一方法是复制任务;
task enableMeA() << {
println "Enable"
}
task disableMeA() << {
shouldRunAfter 'taskAwork'
println "Disable"
}
task enableMeB() << {
println "Enable"
}
task disableMeB() << {
shouldRunAfter 'taskBwork'
println "Disable"
}
task taskAwork(){
shouldRunAfter 'enableMeA'
println "do work in A while disabled"
}
task taskA(dependsOn: disableMeA, taskAwork, enableMeA){
}
task taskBwork(){
shouldRunAfter 'enableMeB'
println "do work in B while disabled"
}
task taskB(dependsOn: disableMeB, taskBwork, enableMeB){
}
task taskC(dependsOn: taskA, taskB){
}
答案 0 :(得分:2)
似乎在您的情况下,您必须为您的任务实施TaskExecutionListener并使用它的beforeExecute
和afterExecute
方法来实现您的逻辑。
这看起来像是:
task taskAwork() << {
println "do work in A while disabled"
}
task taskBwork() << {
println "do work in B while disabled"
}
task doAllWorkTask(dependsOn: [taskAwork, taskBwork]){
}
gradle.taskGraph.addTaskExecutionListener new WorkTasksExecutionListener()
class WorkTasksExecutionListener implements TaskExecutionListener {
@Override
void afterExecute(final Task task, final TaskState state) {
if (task.name.contains('work')) {
println('Enabling smth before execution of work task')
}
}
@Override
void beforeExecute(final Task task) {
if (task.name.contains('work')) {
println('Disabling smth after execution of work task')
}
}
}
这里指定了2个任务,这些任务执行某些操作并且需要在每个任务之前和之后运行一些常见的loigic。要实现此通用逻辑,请使用WorkTasksExecutionListener
实现TaskExecutionListener
接口并在taskGraph
中注册为侦听器。
WorkTasksExecutionListener
实施TaskExecutionListener
:beforeExecute
和afterExecute
的两种方法。这个方法在每个tsk执行之前和之后被调用,因此在它的实现中添加了检查任务是否执行某些工作的条件,如果是,则执行一些额外的逻辑。
在这种情况下的输出将是:
:taskAwork
Enabling smth after execution of work task
do work in A while disabled
Disabling smth before execution of work task
:taskBwork
Enabling smth after execution of work task
do work in B while disabled
Disabling smth before execution of work task
:doAllWorkTask
答案 1 :(得分:0)
默认情况下,Gradle不会运行最新的任务。 如果任务的TaskOutputs属性未被更改,则该任务被视为最新。
如果要在同一执行期间多次运行任务,可以使用upToDateWhen属性定义一个谓词,只要您希望任务再次运行,该谓词将返回 false :
task myTask() {
outputs.upToDateWhen {some_condition}
// Do some stuff
}