How to run a single gradle task from command line

2019-04-19 03:35发布

问题:

In my project I have several tasks in my build.gradle. I want those tasks to be independent while running. ie I need to run a single task from command line. But the command "gradle taskA" will run both taskA and taskB which I do not want. How to prevent a task being running?.

Here's a sample of what I am doing.

   task runsSQL{
    description 'run sql queries'
    apply plugin: 'java'
    apply plugin: 'groovy'

    print 'Run SQL'  }

task runSchema{
    apply plugin: 'java'
    apply plugin: 'groovy'

    print 'Run Schema' }

Here's the output I'm getting.

回答1:

You can use -x option or --exclude-task switch to exclude task from task graph. But it's good idea to provide runnable example.



回答2:

I guess the point that you missed is that you dont define tasks here but you configured tasks. Have a look at the gradle documentation: http://www.gradle.org/docs/current/userguide/more_about_tasks.html.

What you wanted is something like this:

task runsSQL (dependsOn: 'runSchema'){
    description 'run sql queries'
    println 'Configuring SQL-Task' 
    doLast() {
        println "Executing SQL"
    }
}

task runSchema << {
    println 'Creating schema' 
}

Please mind the shortcut '<<' for 'doLast'. The doLast step is only executed when a task is executed while the configuration of a task will be executed when the gradle file is parsed.

When you call

gradle runSchema

You'll see the 'Configuring SQL-Task' and afterwards the 'Creating schema' output. That means the runSQLTask will be configured but not executed.

If you call

gradle runSQL

Than you you'll see:

Configuring SQL-Task :runSchema Creating schema :runsSQL Executing SQL

runSchema is executed because runSQL depends on it.



标签: java gradle