Fail a task if another task has not been run

We have a primary compilation task that does not have a clean way of checking if it’s up-to-date and a duration of about 40 mins. We have some supplementary tasks that depend on the outputs of the primary compilation task. We do not want to automatically run the first task because of the long duration. I came up with the below approach, but would like to know if there’s a recommended way to handle this kind of case.

task second() {
    doLast {
        if (! file('created_by_primary').exists()) {
            def errMessage = 'My error'
            throw new Exception(errMessage)
        // actual work in 'second' task
second.mustRunAfter first


I think that approach is fine for a small detail. However if it gets more complicated maybe a concrete task in buildSrc vs just a script task would be the best route. That way you can specify the input file and leverage the Gradle api to do better incremental inspections. The InputFile annotation allows gradle to better analyze if a task needs to be run or not and if the file is missing. The entire task api can be really powerful IF you need more complexity than what you have here.


open class SecondaryTask {
  val createdByPrimary: RegularFileProperty = project.objects.fileProperty().apply {

  fun execute(incrementalTaskInputs: IncrementalTaskInputs) {
    if(incrementalTaskInputs.isIncremental) {
    // do work

Then just register the task in build script

task second (type: SecondaryTask)
second.mustRunAfter first

If the first task actual has an output then you can actually wire the output into the second task.


Info for project.objects object that i am referencing can be found here:

The task api can be found here: