What is a Gradle Task.

Lets first create a gradle file build.gradle with the following contents in it.

group 'com.ekiras'
version '1.0-SNAPSHOT'

apply plugin: 'java'

sourceCompatibility = 1.8

repositories {

dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'

Now, lets run the the following command from terminal in the root directory where build.gradle is saved.

gradle tasks

It will give the list of all the tasks that are defined. It includes both gradle default tasks and custom tasks.

Now, you can run any defined task using the command.

gradle <task-name>

How to write a Custom Task in Gradle.

  1. A task in gradle is an imlpementation of org.gradle.api.Task interface.
  2. Task interface has two methods doLast() and doFirst() which can define the order of task execution.
    • doFirst(Closure action) - This adds the given closure to the beginning of this task's action list.
    • doLast(Closure action) - This adds the given Action to the end of this task's action list.
  3. Other useful methods are
    • getName() - returns the name of the task
    • getPath() - returns the fully qualified path of the task
    • mustRunAfter(Object... paths) - task should run after the given tasks
    • setGroup(String group) - Adds the task to a specified group.
    • setDependsOn(Iterable<?> dependsOnTasks) - set a list of tasks this task depends on.

You can see Full List of Methods in Task interface in the official documents.

Syntax for writing a task is as follows.

// Simple Task
task core(){
// do stuff

// Task which depends on some other task

task main(dependsOn : 'core'){
// do stuff

So we can write the tasks as follows.

task A {
doLast {
println 'Running task A'

task B(dependsOn: A) {
doLast {
println 'Running task B'

task C(dependsOn: [A, B]) {
doLast {
println 'Running task C'

task D(dependsOn: [A, C]) {
doLast {
println 'Running task D'
  1. We can run any task using command gradle <task-name>.
  2. To run multipe tasks in one step you can use command gradle <task-name> <task-name> <task-name>. It will run the tasks in the defined list specified.


gradle <task-name> <task-name> <task-name> will only trigger tasks in this order, but task run list is still defined by tasks definitions that is if a tasks depends on any other task then taht task will be executed first. Also a task is run only once even if it is defines many times. gradle A A A is equivalent to gradle A.