Search code examples
javagradlegroovybuild.gradle

Gradle task runs even if upToDateWhen returns true


I am learning Gradle. I have a task where I have used upToDateWhen method . It is hardcoded to always return true. I heard that if it is true the method is considered up to date and it wont run. But when I execute the task it runs for the first time and then it stops running from the second time saying its upto date. I thought it wont run even for the first time. Am i missing something. Please shed some light .

task inputOutputCheckWithMethodCall(group:'Learn-Task-Execution',description:'This task is used to learn how gradle executes tasks by evaluating input and output through method call during execution time'){
    outputs.upToDateWhen {true}

       doFirst{

        println 'Executing task inputOutputCheckWithMethodCall'  

    }
       }

Solution

  • The outputs being up to date is only part of the calculation as to whether a task is up to date. See https://github.com/gradle/gradle/issues/2467#issuecomment-315184626

    outputs.upToDateWhen { true } doesn't mean "the task is up-to-date." It just means that the outputs are up-to-date for that particular spec. Gradle will still do its own up-to-date checks.

    The other thing that may be confusing is where the task's actions are defined. If the actions are defined in the build script, the build script itself is an input to the task. So changes to the build script will make the task out-of-date.

    So if I had a task like:

    task myTask {
        def outputFile = file("output.txt")
        outputs.file outputFile
        doLast {
            outputFile.text = "Done"
        }
    
        outputs.upToDateWhen { false }
    }
    

    Whenever I run this, myTask is out-of-date. If I switch the false to true, the first time I run it, the task is out-of-date still (because the buildscript changed). When I run it again, it would be up-to-date (all inputs are the same). You'll see this at --info level logging.

    Task ':myTask' has additional actions that have changed