“A task is a piece of work that Gradle builds perform.”
Gradle Build script defined for one or more projects. Each project build is made up of multiple tasks. For Example:
- Compiling classes
- Storing classes to target
- Copy files from resources to target.
- Making Jar
- Generating ]ava doc etc.
The Gradle build has common in-built tasks to build and run an application. You can also define your own tasks to customize the build process.
Topics Covered
- Structure of Task
- Define your Own Tasks
- Define Default Task
- Task Dependencies or Order
- Use External Dependencies on Task
- Dynamic Tasks
- Execution of Tasks
- Get the list of Gradle In-built tasks
Structure of Task
To define your own task in build.gradle, you need to use task keyword to define a custom task. Gradle follows this task structure :
task myTask{
println 'Execute My Task'
doFirst{
println 'Execute doFirst 2 with in MyTask'
}
doFirst{
println 'Execute doFirst 1 with in MyTask'
}
doLast{
println 'Execute doLast 1 with in MyTask'
}
doLast{
println 'Execute doLast 2 with in MyTask'
}
}
Herewith defining tasks you can also add behavior to existing tasks by implementing the actions. in the Gradle task, we can add doFirst or doLast or both actions. You will
-
- doFirst: (Optional)
This action executes at the beginning of task execution.
-
- doLast: (Optional)
This action executes at the end of the task execution.
doFirst and doLast can be added in task multiple times and execution of these all doFirst and doLast will be in sequence of implementation.
Output ->gradlew myTask -q
Execute My Task
Execute doFirst 1 with in MyTask
Execute doFirst 2 with in MyTask
Execute doLast 1 with in MyTask
Execute doLast 2 with in MyTask
Define Your Own Tasks
Gradle provides lots of ways to define these tasks as follows:
- Simple Declaration
task myTask { doLast { println 'FacingIssuesOnIT' } }
- Define Task with Symbols use the symbol (<<) doLast or (>>) doFirst
task myTask << { println 'FacingIssuesOnIT' }
- Alternate way with Symbol
task (myTask) << { println 'FacingIssuesOnIT' }
- String Task Name
task ('myTask') << { println 'FacingIssuesOnIT' }
- Define task by create() method
tasks.create (name : 'myTask') << { println 'FacingIssuesOnIT' }
The above are ways to define tasks in Gradle. If you copy each way and try to execute a task with below command it will return the same result.
Output -> gradlew myTask -q
FacingIssuesOnIT
Define Default Task
You can define your default tasks in build.gradle file with keyword defaultTasks. These tasks will be executed when you have not specified any task for execution.
defaultTasks 'clean', 'run'
task clean {
doLast {
println 'Default System Cleaning!'
}
}
task run {
doLast {
println 'Default Running!'
}
}
task other {
doLast {
println "I am not a default task!"
}
}
In this example mentioned default tasks as ‘clean’ and ‘run’. These tasks will execute when no task specified for execution. Let’s execute this command and see the output.
output:
Output -> gradlew -q
Default System Cleaning!
Default Running!
Output-> gradlew other -q
I am not a default task!
Task Dependencies and Order
Sometimes one task depends on other tasks and needs to define execution order of tasks. These task dependencies and task order are controlled by these methods:
- dependsOn: Use to add the given dependencies to this task.
tasks.create('A') tasks.create('B').dependsOn('A')
Executing B here require to execute task A first.
- mustRunAfter: It defines the ordering of tasks.
tasks.create('C') tasks.create('D').mustRunAfter('C')
Execution of task D doesn’t require C but if both tasks are included for execution task C will execute first then task D.
- shouldRunAfter : It’s also define ordering of tasks but not restrictive as above. This ordering ignored in two cases:
- If using that rule introducing a ordering cycle.
- If using parallel execution and all dependencies are satisfied except “should run after” then task will execute even it’s not satisfied “should run after” condition.
See Also: Gradle: Task Properties, Methods, and Actions
Example: Here is an example to use dependsOn function to show dependencies of a task in build.gradle file.
task hello {
doLast {
println 'Hello!'
}
}
task detail {
dependsOn hello
doLast {
println "You are in 'Facing Issues on IT'"
}
}
In this example when run task detail then it’s dependent task hello will also execute.
Output
Output->gradlew detail -q
Hello!
You are in 'Facing Issues on IT'
Note: Always define your task before use it. If not the following order you will get MissingPropertyException.
Use External Dependencies In Task
You can use buildScript function build.gradle to declare repositories and dependencies required for the task.
import org.apache.commons.codec.binary.Base64
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath group: 'commons-codec', name: 'commons-codec', version: '1.2'
}
}
task encodeText {
doLast {
def byte[] encodedString = new Base64().encode('Facing Issues On IT\n'.getBytes())
println 'Before Encode: Facing Issues on IT'
println 'After Encodeing:' + new String(encodedString)
}
}
In this example, for task encodeText is used Base64 class to encode text. So here you need to mentioned repositories and dependencies required to import the Base64 class
Output->gradlew encodeText -q
Before Encode: Facing Issues on IT
After Encodeing:RmFjaW5nIElzc3VlcyBPbiBJVAo=
Dynamic Tasks
By using Groovy or Kotlin scripting language, You can create tasks dynamically.
- Create a task by Loop
This code will create 5 tasks by the loop (0 to 4). These task name as task0, task1, task2, task3, task4.
5.times { counter ->
task "task$counter" {
doLast {
println "This is task number $counter"
}
}
}
task1.dependsOn task2, task3
Suppose to execute a particular task2 run command as
Output->gradlew task2 -q
This is task number 2
Output->gradle -q task1
This is task number 2
This is task number 3
This is task number 1
Execution of Tasks
Here are different cases to execute tasks in gradle.
- Execute Specific Task
In all these above examples you have seen the below command to the execution of the task.gradlew taskName -q
Here -q represents log level as QUIET which shows logs statement for QUIET level and no verbose log statement. See Also : Gradle: Logging Configuration
- Execute Default Task
If no task specified then only default task will execute.gradlew -q
- Execute Multiple Tasks
gradlew taskName1 taskName2 -q
- Exclude Tasks
Use –exclude-task to exclude tasks.gradlew taskName1 taskName2 --exclude-task test -q
In this example test will not execute.
- Execute Task in multi-Project build
Use colon(:) to specify task related to sub project.gradlew mySubproject:taskName
Gradle In-built Tasks
Gradle is having a big list of in-built common tasks that not required any implementation. These can be executed by names only.
To get a list of all Gradle in-built tasks by executing the below command.
gradlew tasks --all
Here is a list of Gradle in-built tasks.
- Build Tasks
- assemble – Assembles the outputs of this project.
- build – Assembles and tests this project.
- buildDependents- Assembles and tests this project and all projects that depend on it.
- buildNeeded – Assembles and tests this project and all projects it depends on.
- classes – Assembles main classes
- clean – Deletes the build directory.
- jar – Assembles a jar archive containing the main classes
- testClasses – Assembles test classes.
- Build Setup Tasks
- init – Initializes a new Gradle build.
- wrapper – Generates Gradle wrapper files
- Documentation tasks
- javadoc – Generates Javadoc API documentation for the main source code.
- Help tasks
- buildEnvironment – Displays all buildscript dependencies declared in root project ‘GradleJavaLibrary
- components – Displays the components produced by root project ‘GradleJavaLibrary’. [incubating]
- dependencies – Displays all dependencies declared in root project ‘GradleJavaLibrary’.
- dependencyInsight – Displays the insight into a specific dependency in root project ‘GradleJavaLibrary’.
- dependentComponents – Displays the dependent components of components in root project ‘GradleJavaLibrary’. [incubating]
- help – Displays a help message.
- model – Displays the configuration model of root project ‘GradleJavaLibrary’. [incubating]
- outgoingVariants – Displays the outgoing variants of root project ‘GradleJavaLibrary’.
- projects – Displays the sub-projects of root project ‘GradleJavaLibrary’.
- properties – Displays the properties of root project ‘GradleJavaLibrary’.
- tasks – Displays the tasks runnable from root project ‘GradleJavaLibrary’.
- Verification tasks
- check – Runs all checks.
- test – Runs the unit tests.
- Other tasks
- compileJava – Compiles main Java source.
- compileTestJava – Compiles test Java source
- prepareKotlinBuildScriptModel
- processResources – Processes main resources.
- processTestResources – Processes test resources.
- Rules
- Pattern: clean: Cleans the output files of a task.
- Pattern: build: Assembles the artifacts of a configuration.
- Pattern: upload: Assembles and uploads the artifacts belonging to a configuration.