Gradle Custom Task Example

By Arvind Rai, October 06, 2014
In this page, we will learn how to define task in Gradle script. We can define our custom task according to our need. We will cover here what is doFirst and doLast in Gradle and how to set execution order of task on another task using dependsOn. We will also see a complete example of Gradle task and will see how to run it.

Declare Custom Task in Gradle

To define task in Gradle, task keyword is used. Find the syntax below.
task taskName {
} 
In Gradle script more than one task can be defined according to need. Within task we need to write command which needs to be executed by this task.

doFirst and doLast in Gradle Task

While executing task, we can define pre and post processing for a task. If we need to process any command before or after of a task, we can do as below. Find the first approach to define doFirst and doLast in Gradle Task.
task time {
    doFirst {
        println 'time in doFirst'
    }
    doLast {
        println 'time in doLast'
    }
} 
Another approach to define doFirst and doLast is given as below.
task msg {
  description = 'Task to display message.'
}
msg.doFirst {
  println 'task msg in doFirst'
}
msg.doLast {
  println 'task msg in doLast'
} 

dependsOn in Gradle Task

If more than one task is there in our Gradle file, then we can set execution order of task by setting dependency of task for any other task. Suppose we have two task as msg and time and if we need to execute time task first, then dependsOn can be used.
msg.dependsOn(time) 

How to Run Task in Gradle

Find the example of a gradle build file consisting of two task.
apply plugin: 'java'
apply plugin: 'groovy'
task time {
    doFirst {
        println 'time in doFirst'
    }
    doLast {
        println 'time in doLast'
    }
}
task msg {
  description = 'Task to display message.'
}
msg << {
  println 'Find your message by msg task'
}
msg.doFirst {
  println 'task msg in doFirst'
}
msg.doLast {
  println 'task msg in doLast'
}
msg.dependsOn(time)
 
Now task can be executed as below.
gradle time
We get output of time task only.
:time
time in doFirst
time in doLast
BUILD SUCCESSFUL 
Now execute msg task.
gradle msg
We get output of both task because msg task depends on time task.
:time
time in doFirst
time in doLast
:msg
task msg in doFirst
Find your message by msg task
task msg in doLast
BUILD SUCCESSFUL 
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us