Looking for a way to force a task that has no input & output to run again on subsequent runs

Can someone please help me to find a way to force a Gradle task to re-run on each call, Gradle is executing it only one. Sample build.gradle to replicate the scenario.

task finalizedByTask {

// setOnlyIf {true}
outputs.upToDateWhen { false }
println “=== Restarting server===”
}

task task1{
doFirst {println “lets task1” }
finalizedBy finalizedByTask
}

task task2 {
doFirst {println “lets task2” }
finalizedBy finalizedByTask
}

task task1task2{
dependsOn task1, task2
println “lets task1task2”
finalizedBy finalizedByTask
}

Are you expecting the finalizedByTask to run multiple times? Each task will execute either 0 or 1 times per Gradle invocation. Perhaps you need a finalizer for each task? Hard to know without more context

Thanks, @Lance for the prompt response, yes I have to run “finalizedByTask” multiple times, after the completion of each task -deployProduct & functionalTests. So I have to run it two times but it is executing only once.

task restartServer{
//Do necessory stuff
}

task deployProduct {
//copy jar in auxPath of server, this will be picked up after server restart
finalizedBy restartServer
}

task functionalTests{
dependsOn deployProduct
//Run tests
//Restart server to clean cache and kills running jobs
finalizedBy restartServer
}

That’s not how gradle works. As I said, a task will never execute twice in a single Gradle invocation. It’s not a method call. I’m guessing you’ll need multiple instances of the same task type, each with slightly different configuration (ie a different directory for each)

Is there any way to add a sudo directory or any other way to manipulate configuration of the task inside task ?

No, don’t do that. Just create separate tasks for each. build.gradle is groovy so you can do in a loop if you like

['A', 'B', 'C'].each { 
   tasks.create("doStuff$it", type: Foo) {
      workingDir "$buildDir/$it" 
      finalizedBy "finalizeStuff$it" 
   } 
   tasks.create("finalizeStuff$it", type: Bar) {
      workingDir "$buildDir/$it" 
   }    
} 
1 Like

Task rule did the trick.

tasks.addRule("Pattern: restartServer<ID>") { String taskName ->
    if (taskName.startsWith("restartServer")) {
        task(taskName) {
            doLast {
                //Perform restart activity here
            }
        }
    }
}

I just need to provide a unique name to task in each finalizedTask block - restartServer1, restartServer2 etc.

Thank you for your valuable support.

Whatever floats your boat, I try to avoid magic naming conventions

@Lance if Gradle api is not designed to run a task twice per gradle invocation, can you please hint me into a good direction on this question? Force rerun a task by another task

I would be very grateful to you.

Thanks in advance