自定义Gradle执行任务不会并行运行

时间:2019-06-02 02:12:35

标签: gradle gradle-plugin gradlew

我的目标是我可以运行./gradlew deployStaging,并并行执行buildDockerStaticbuildDockerBackend,并且在完成两个任务之后,deployStaging将运行。使用下面的代码,任务可以串行运行。我已经尝试了一些方法,但是buildDockerStaticbuildDockerBackend总是串行运行。

tasks.register("buildDockerStatic", BuildDockerStatic) {
    workingDir rootDir
}

tasks.register("buildDockerBackend", BuildDockerBackend) {
    workingDir rootDir
}

//noinspection GroovyAssignabilityCheck
task deployStaging() {
    dependsOn tasks.buildDockerStatic
    dependsOn tasks.buildDockerBackend

    doLast {
        exec {
            workingDir rootDir
            commandLine 'sh', './scripts/build_deploy_staging.sh'
        }
    }
}

class BuildDockerStatic extends AbstractExecTask<BuildDockerStatic> {
    BuildDockerStatic() {
        //noinspection GroovyAssignabilityCheck
        super(BuildDockerStatic)

        commandLine 'sh', './scripts/build_static.sh'
    }
}

class BuildDockerBackend extends AbstractExecTask<BuildDockerBackend> {
    BuildDockerBackend() {
        //noinspection GroovyAssignabilityCheck
        super(BuildDockerBackend)

        commandLine 'sh', './scripts/build_backend.sh'
    }
}

1 个答案:

答案 0 :(得分:0)

要并行运行,需要将构建任务放置在子项目中。

它们应包含doLast;否则将在调用例如时执行。 gradle clean。也许使用纯task {..}的定义就足够了。


并行::来自文档Gradle:parallel execution

  

通过使用--parallel开关,您可以强制Gradle并行执行任务,只要这些任务位于不同的项目中即可。


请参见下面的修改示例;它将并行运行两个子任务(睡眠和日志)。

它可以与gradle clean deployStaging --parallel

一起运行

多项目结构

build-backend
  +--build.gradle
build-static
  +--build.gradle
build.gradle
settings.gradle

build-backend/build.gradle

apply plugin: 'base'
task buildDockerBackend {
  doLast{
    exec {
      println 'BuildDockerBackend: started at ' + new java.util.Date()
      workingDir rootDir
      sleep 4000
      //commandLine 'sh', './scripts/build_backend.sh'
      commandLine 'echo', 'task: build-backend'
      println 'BuildDockerBackend: done at    ' + new java.util.Date()
    }
  }
}

build-static/build.gradle

apply plugin: 'base'
task buildDockerStatic {
  doLast{
    exec {
      println 'BuildDockerStatic: started at ' + new java.util.Date()
      workingDir rootDir
      sleep 8000
      //commandLine 'sh', './scripts/build_static.sh'
      commandLine 'echo', 'task: build-static'
      println 'BuildDockerStatic: done at    ' + new java.util.Date()
    }
  }
}

build.gradle

apply plugin: 'base'
task deployStaging {
  doLast {
    exec {
      workingDir rootDir
      //commandLine 'sh', './scripts/build_deploy_staging.sh'
      commandLine 'echo', 'task: deploy-staging'
    }
  }
}
deployStaging.dependsOn ':build-static:buildDockerStatic'
deployStaging.dependsOn ':build-backend:buildDockerBackend'

settings.gradle

include 'build-static'
include 'build-backend'