how to write gradle task

Understanding Gradle Tasks

Learn how to create, use, and see the outcomes of tasks, and more.

Dmitrii Leonov

Dmitrii Leonov

Better Programming

You may rarely deal with Gradle Tasks , and most of the time, new Task s are added either as a part of a plugin or as a copy-pasted piece of code from libraries’ “How to start” guide. Having no understanding of how Tasks work, their structure, and their lifecycle makes developers more likely to stay away from adding any changes to those tasks, even if there is room for improvement.

In this article, let’s try to understand what are Gradle Tasks, how they are created and used, and what forms can they take.

Basic things you should know about a Task :

  • A Task is an executable piece of code that contains sequences of actions.
  • Actions are added to a Task via the doFirst{} and doLast{} closures.
  • A list of available tasks can be accessed by executing ./gradlew tasks .

To better understand the structure, syntax, and relationship between Gradle project entities, look at my earlier article .

Further in the article, given you are testing code in an Android project or any other project with Gradle wrapper in it, executing task X means running ./gradlew X on Mac or gradlew.bat X on Windows.

What Do Tasks Look Like?

As you may already know, in Gradle, things come in many different forms, and Tasks are no exception. Task definition can be done in many different ways, most commonly in one like this:

When running the taskName1 from above, the output is not so obvious:

But wait, it gets more confusing. Let’s add an alternative and more explicit form of the same task, just named differently:

The code above is more descriptive and speaks for itself. As you can see, we are calling create() on the project’s TaskContainer object tasks , after which we configure a group property of the newly created Task and add actions to the list.

Let’s execute our taskName1 once again and look at the output:

As you can see, “Why is this printed first?” is printed twice. So why is it happening, and where is it coming from?

Build lifecycle and phases

Unlike the tasks declared above, most tasks depend on each other. To execute a task, Gradle has to understand the tasks available in the project and what dependencies the task has. For that, Gradle creates a directed acyclic dependency graph and executes tasks according to it.

Do not get shocked by the term directed acyclic dependency graph. All it means is that:

  • Tasks and their dependencies are composed into a graph structure where nodes represent tasks, and vertices/lines represent dependencies.
  • Directions of the vertices represent how one task depends on other tasks.
  • Acyclic means that there are no such tasks A and B where both are dependent on each other directly or transitively.

There are three build phases:

  • Initialization — starts with creating a Settings object according to settings.gradle file and builds a hierarchy of sub-projects (in Android Studio referred to as modules) included in the Gradle project.
  • Configuration — configures each project discovered in the initialization phase, then goes to respective build.gradle files and configures Project instances and builds a graph of tasks on which the targeted task depends directly or transitively.
  • Execution — executes a task and all the tasks depend on the task executed, which is known from the configuration phase.

Knowing build phases, we can now understand that, although we do not execute taskName2 directly, the code inside the configure{} closure is still executed during the configuration phase, which causes Why is this printed first? to appear twice.

Can this be avoided?

Yes, for that, Gradle has Configuration Avoidance API . It is a recommended method for creating tasks that help to reduce configuration time by avoiding working with Task instances directly and instead doing it using TaskProvider , and creating a reference to a Task .

Using TaskContainer.register() will prevent a task from being included in the configuration phase unless the registered task is executed directly or is included in the dependency graph of the task being executed.

Try running taskName1 once again and see that the output is the same as it was before adding the taskName3 . At the same time, running the taskName3 adds one more line to the configuration part of the logs because now it is included in the configuration phase together with taskName2 and taskName1

Why do we have doFirst and doLast?

Why is simply putting Actions in a correct sequence of execution not enough, and why do we need doFirst{} and doLast{} ?

For a moment, treat these closures as something to execute before and after X. What is X, then?

To answer that, let’s define a simple task class and run a task of the newly created task class, demonstrating one more way a task can be defined.

Putting the configuration-related part of logs aside, the output for both of the tasks of the newly defined type will be:

So the Actions supplied to doFirst{} and doLast{} are executed before and after the action(s) annotated with @TaskAction .

As you can see from code snippet #4, the CustomTaskType extends DefaultTask class, a basic class you can extend to implement a custom task class. Gradle has several useful, ready-to-use task types that you can find in Gradle‘s Github .

What else to know about Gradle Tasks?

Task s have outcomes that indicate what happened with the tasks during the build process. Intuitively, you may guess that a task can have three outcomes — not executed, executed using cached results, and just executed.

In Gradle, there are five task outcomes:

  • NO-SOURCE — a task is unexecuted because the input data required for its execution was not found. An example of an input can be a file annotated with @InputFiles @SkipWhenEmpty and @Incremental that failed to be produced by a prior task.
  • SKIPPED — skipped for some reason. Such reason can be — a task marked as enabled = false in the task’s body or excluded from the execution process via command line argument -x and a few others.
  • UP-TO-DATE — a task result has not changed since the last build and can be reused. This happens as a part of the Incremental build feature.
  • FROM-CACHE — the task can be taken from the previous builds. It uses a feature called Task output caching . It’s an advancement of Incremental build used in UP-TO-DATE as it can reuse remote caches by getting them from CI. Unless you have org.gradle.caching=true in or you use --build-cache flag when executing a task, this is not applied to your builds. For a task to be catchable, it should be annotated as @CacheableTask .
  • EXECUTED — the task is executed successfully. This label is not displayed in logs.

To make these outcomes visible, use a flag --console=plain , for example, in an Android project, you can use it on assembleDebug :

Ideally, a build should have as many UP-TO-DATE and FROM-CACHE to have a faster execution time.

Task ordering and dependencies

It has been mentioned that a Task can depend on other tasks, but what does it look like in code? These indicators below denote that tasks are dependent on one another:

Explicitly define relationships between two tasks:

  • dependsOn — task X { dependsOn Y } , task X requires task Y for its execution, and if Y fails to execute, the execution of X will not happen.
  • finalizedBy — task X { finalizedBy Y } task Y will be executed after task X even if the X failed to execute or was skipped.

Input and output annotations:

  • @OutputFile and @InputFile — is an implicit way to create a dependency by annotating the inputs and outputs of tasks. This approach requires configuring tasks that have matching inputs and outputs.

Tasks can be defined in many ways, but not all are equally good. For the configuration time, utilize Configuration avoidance API and register tasks using TaskContainer.register() .

It is good to understand the Task outcomes to identify weak points of the build and try to cache task execution results where possible by properly structuring dependencies between tasks and putting Incremental build and Task output caching mechanisms to work.

Dmitrii Leonov

Written by Dmitrii Leonov

Android Developer | Getting better at my craft by sharing knowledge!

Text to speech

Gradle Tutorial for Complete Beginners

how to write gradle task

Have you heard of Gradle, but you’re not really sure what it is , why you should use it , and how to get started ? This tutorial answers all of these questions and helps you take your first steps with this powerful build tool.

In this Gradle tutorial you’ll learn:

why we need help from build tools to build Java applications

why Gradle is a great choice for building Java applications (better than Maven or custom scripts)

how to create your first Gradle Java project, understanding the fundamentals of projects, build scripts, tasks, and plugins

Gradle gets more usage year-by-year as developers realise the productivity benefits. Benefits that you too will be able to take advantage of in your own project. So let’s get right into it!

1. Who this tutorial is for? #

If you’ve never used Gradle before you’re in the right place. This is a tutorial for complete beginners after all. If you have used Gradle, but are feeling confused and want to understand the basics, this is for you too.

Ideally, you should have some Java knowledge as this tutorial is focussed on building Java applications.

2. Why do we need build tools? #

First up, lets get right back to basics to understand why we need build tools , also known as build automation tools , anyway.

Let’s consider a simple Java application and what needs to be done to transform it from just being some source code in a repository, to being an application ready to be executed.

Here’s the code for the application. Yes, it may well be the same as the first Java application you ever wrote, listed on a thousand tutorial websites.

how to write gradle task

It’s just a single Java class within a directory structure. This class lives in a file with a .java extension, also known as a source file . It’s the code that we as developers write, and in theory can read and understand too!

Whether you have a tiny application like this, or a huge application, it’s still just source files in a directory structure. Maybe there’ll be some resources too.

But how are you going to run this code?

Well, you’re going to have to compile it first. That’s right, you need to transform the .java file into a .class file. Or in other words, transform your application from human readable code to machine readable code, or in technical lingo bytecode .

how to write gradle task

This process of generating the bytecode is called compilation . Bytecode can be run on the Java Virtual Machine , the JVM, which is where applications can work their magic and fulfil business requirements. Or at least print out Hello World!!

Compiling without a build tool #

Compiling Java code is actually something you can do without a build tool. The Java Development Kit (JDK) comes with the Java compiler command javac . You call javac with a list of all the .java source files to be compiled.

That’s not going to be much fun to do by hand! 😮

It’s also very likely that once you get beyond Hello World applications you’ll need to use functionality provided by 3rd party libraries , or more specifically jar files. For example, Spring Boot, Apache Commons Lang 3, or Guava.

That’s where the compile classpath comes in. You need to add to it all the jar files referenced by code in your application in order for compilation to work.

Generating the compile classpath is going to be a real pain to do manually. Especially if you consider the tens or hundreds of libraries used by even basic Java applications these days.

Build tools to the rescue #

I think you get where I’m going with this. Compiling Java code manually gets really tedious really fast. This is the main reason build tools exist. To make compilation a simple, error free, and repeatable process. 

There are of course other compelling reasons that build tools exist. Here are two important ones.

testing ensures that software fulfils its requirements. Without a build tool you’d have to manually run the tests with the java command, and collate the results. Build tools makes life a lot easier.

packaging your application means putting it into a format that can easily be published and deployed. For Java applications this is normally a .jar or .war file, or perhaps a Docker image. Build tools can script this process so you don’t have to remember long complicated commands.

3. The Gradle build tool solution #

Gradle is a build tool designed specifically to meet the requirements of building Java applications. Once it’s setup, building your application is as simple as running a single command on the command line or in your IDE.

gradlew build

That includes, compiling, testing, and packaging your application, all with one command. We’ll cover exactly what this command does later.

But how does Gradle know how to build your application? #

On a high level, you have to describe:

what type of application you’re trying to build, for example Java

any libraries your application depends on, or in other words its dependencies

any other configuration specific to your application, such as special compile or testing options

In Gradle you provide this configuration in a file called a build script . It gets committed into your application repository, which means anyone can clone your repository and immediately build the application consistently.

Much better than a custom script #

If you’re wondering why you should use yet another tool for this process, and not create your own script, then consider this. Gradle is designed to perform extremely quickly. It has many optimisations that would be very time consuming to create in a custom build script.

For example, once you’ve compiled your application once, when you try to compile again after not having changed anything, Gradle knows it doesn’t need to recompile. This feature, called incremental build , works in many other scenarios and means less waiting around for developers.

how to write gradle task

Gradle incremental build feature (simplified)

Aside from performance, Gradle has an advanced dependency management system . At a basic level, when you define dependencies and run your build, Gradle downloads them automatically from the internet. This makes managing and upgrading dependencies simple, a feature which you wouldn’t get using a custom build script.

So maybe I’ve convinced you that using Gradle is a better idea than creating your own build script? But why Gradle, and why not some other build tool? Or more specifically, the very big elephant in the room, Maven.

4. Maven vs. Gradle #

We don’t have time for a full comparison of these two build tool giants (check out this video for that). But in 2004 when Maven was first released, it was an advanced Java build tool for the time.

Gradle came 4 years later though, and was designed to solve some of Maven’s shortcomings:

Gradle made defining your build less verbose with a code-based build script rather than XML build file

with Gradle’s code-first approach, writing custom plugins and reusing build logic was a lot easier. Very helpful in larger projects.

Gradle was designed with developer productivity in mind, and it performs a lot faster than Maven

Gradle is now the most popular build tool for open source JVM projects on GitHub . Any time you invest learning this tool is well spent, as in my opinion it’s currently the best option for building Java applications and will continue to be for years to come.

We’ve covered a lot of theory so far, so let’s jump right in and see how to install Gradle, then how to create a basic project.

5. Installing Gradle #

Let’s be honest, installing software is never glamorous, so I’ll cut to the chase.

Prerequisites #

Since Gradle runs on Java, you need Java version 8 or above to be installed.

You can verify this by running this command.

If you don’t have Java installed you can follow this guide .

Get latest Gradle version #

Head over to and follow the instructions for installing Gradle in Windows, or using the SDKMAN! or Homebrew package managers. 

Here’s how it works on Windows.

download the latest Gradle distribution (choose binary-only option)

create a Gradle directory where you’ll be able to add any new versions of Gradle (e.g. C:\Gradle )

copy the unzipped directory there

update the PATH environment variable to include the Gradle /bin directory. Hit the Windows key, type environment variables , and hit enter. Select Environment Variables . Under System variables double click PATH . Select New and paste in the path to the bin directory (e.g. C:\Gradle\gradle-7.2\bin ). Select OK three times.

To double check it’s working, open a command prompt and type gradle --version .

If you see output that looks like this, you’re good to continue.

6. Creating a Gradle project using gradle init #

With Gradle installed on your machine, you can easily create skeletons for new Gradle projects on the command line. We’re going to create the most basic type of project available, understand its different components, then extend it to build a Java application.

Following along #

Follow along with the steps in this tutorial yourself to understand the concepts more thoroughly.

all you need is the command line and a simple text editor

instructions are provided for Windows & Linux/Mac environments

if you get stuck you can always refer to the accompanying GitHub repository

Create a new directory called gradle-tutorial wherever you want, change directory into it, then type gradle init and hit enter. This setup wizard navigates us through the project creation process with three questions

what type of project to generate : type 1 for basic project, and hit enter

which language to use for the Gradle build script : since the build script is written as code, it can use either the Groovy or Kotlin language. We’ll be using Groovy, so type 1 and hit enter.

what to use for the project name : accept the default of gradle-tutorial , the same as the directory name, so just hit enter

Different versions of Gradle may ask additional questions, but just accept the defaults by hitting enter.

That’s it, Gradle has created a project for us!

What is a project? #

Before we explore it further though, let’s define what a Gradle project actually is.

The project is the highest-level construct representing the application you want to build, including the configuration of how to build it. So if you’ve got an application’s source code sitting in a repository, an accompanying Gradle project also gets committed into the repository with all the information needed to build the application.

7. Gradle project files #

Here’s what Gradle created when we ran gradle init .

how to write gradle task

To keep this concise, we’ll run through just the most important files used in the rest of this tutorial, starting with the most important.

settings.gradle (1) sets up some high-level configuration for the project, in our case the project name.

The file is written in Groovy, the essentials of which we’ll cover shortly. It’s important to set the project name like this, otherwise Gradle will by default use the directory name, which isn’t always reliable.

build.gradle (2) is the build script configuration file describing your application to Gradle so it can build it. For example, here you might say that your application is a Java application with a particular set of dependencies. Like settings.gradle , build.gradle is also written in Groovy.

Right now it’s empty with just some comments, which means nothing will get built. That’s fine, since we’re just exploring the project structure right now, and will add to this shortly.

gradlew and gradlew.bat (3) are known as the Gradle wrapper scripts, for Linux/Mac and Windows respectively. These let you build an application without having to download and install Gradle like we did earlier. When the wrapper is executed, it will automatically download Gradle and cache it locally. Normally you always build your application with the wrapper, as it ensures it gets built with the correct version of Gradle.

The only reason we installed Gradle separately earlier was so that we could run the gradle init command in an empty directory to initialise this skeleton project. For the rest of this tutorial when we interact with our Gradle project we’ll always use the wrapper.

.gitignore (4) configures Git so that the .gradle and build directories aren’t committed into version control. Everything else gets committed though.

The .gradle directory is a local cache managed by Gradle, and the build directory is where Gradle creates any build outputs such as compiled Java code or jar files. You’ll see how that works shortly, when we get onto building a real Java application.

8. Using the Gradle wrapper #

This Gradle project doesn’t do anything yet. Its build.gradle is empty, and besides, there’s no code here to compile. But we can still interact with it, using the wrapper script.

On Windows type gradlew tasks . On Linux/Mac, that’s ./gradlew tasks . Hit enter.

What we see here are a list of the Gradle tasks currently available to run in this project. Oh, we didn’t define tasks yet? OK then…

9. Projects, build scripts, tasks, & plugins #

Let’s go back to basics then, and learn how the four fundamental Gradle components of projects, build scripts, tasks, and plugins work harmoniously together to build applications.

You already know that the project is the highest-level Gradle concept. It’s a container for everything that Gradle knows about your application.

how to write gradle task

Build script #

Each Gradle project can have a build script . You already encountered this with the build.gradle file in the gradle-tutorial project. Once again, this is where you tell Gradle about your application through configuration, and Gradle uses that information to build it.

Gradle tasks are individual build actions you can run from the command line. You might have a task to compile your Java code, a task to test the code, and a task to package the compiled classes into a jar file. We saw a list of all the available tasks earlier when we ran gradlew tasks .

The way you run a task is by passing its name to the Gradle wrapper.

gradlew <task-name> on Windows

./gradlew <task-name> on Linux/Mac

For the rest of this tutorial I’ll use the Windows version, but use whatever is relevant to your environment.

We used this same syntax earlier when we ran gradlew tasks . Slightly confusingly, tasks itself is a Gradle task which you can execute to print out all the tasks. This task comes for free with any Gradle project, as do all the other tasks shown earlier. We won’t go through them all, but you can always try running them yourself.

Importantly, custom tasks can be defined in the build script e.g. task A , above.

The last big concept to wrap your head around is the Gradle plugin . When you apply a plugin in your build script, it automatically adds tasks to your project which you can run to achieve some particular outcome e.g. task B & task C , above.

As a real-world example, the Gradle Java plugin , which we’ll try out soon, automatically adds tasks to compile, test, and package your application, and much more. Using plugins means you don’t have to reinvent the wheel, as almost anything you want to do with Gradle is covered by either a core or 3rd party plugin.

With this mental model of the four fundamental components, projects , build scripts , tasks , and plugins , we’re almost ready to start adding to the build script. But before that, if you understand just a few key concepts of the Groovy programming language, the build script will make a lot more sense.

10. Groovy essentials #

Groovy is a language which, like Java, runs on the Java Virtual Machine, the JVM. Groovy was chosen as the language for Gradle build scripts because of its dynamic nature, allowing your build to be concisely configured using what’s called the Gradle Groovy DSL (domain specific language). Writing Gradle build scripts involves writing Groovy code, but doing it in a way that uses the Gradle APIs.

Since you already know some Java, you’ll pleased to know that Groovy is quite similar. 😊

Here are some key differences with Groovy, which Gradle makes use of in its build scripts.

  • it’s a scripting language, so you can write code outside of a class and execute it

it’s dynamically typed, so you can use the def keyword instead of providing a type (see above)

semicolons at the end of a line are not required. Thank goodness! (see above)

round brackets () are optional when passing parameters to a method, if the method has at least one parameter

  • you can define closures using curly brackets {} . Closures are blocks of code that can get passed around and executed at a later point.
  • if you’re calling a method with multiple arguments using round brackets () , if the last argument is a closure, then it can go outside of the brackets.

Importantly, you don’t need to know much Groovy to work with Gradle build scripts. That’s because the Gradle Groovy DSL uses only a subset of the Groovy language features. What’s shown here is enough Groovy knowledge for you to get started.

So let’s move onto writing a simple build script to build a Java application, and I’ll point out the Groovy language features as we go.

11. Building a Java project #

First up, we need some Java code to actually build, so let’s add a single class to our java-tutorial project. By default Gradle expects Java classes to live in src/main/java , which is good since you’ll always know where to look, whatever project you’re working in.

create the directory src/main/java

create a package of com.tomgregory . If you want to use your own name, go ahead, I won’t be offended!

in that package create a new Java source file

add the following GradleTutorial class with a main method which prints out a highly amusing string

OK, so we’ve got our class. How about we build this bad boy then?

Applying the Java plugin #

Remember from earlier that we need Gradle to take this .java source file, and compile it into a .class file.

In build.gradle delete the comment, then we need to apply the Java plugin, which like I said before adds tasks into our project. The way we apply a plugin is to call the plugins method and pass a closure.

What we’re seeing here is just calling a method called plugins with a closure as an argument. Within the closure we call the id method, and pass the string java . That’s it!

But what tasks has the Java plugin added? Well, to find out let’s run the tasks task again with gradlew tasks . Yes, the task called tasks which prints out all the tasks. Try saying that while standing on your head! 🤸

how to write gradle task

You’ll see a load of new tasks, but we’re just going to focus on the build task, which as it says assembles and tests this project .

Let’s run the build task using the Gradle wrapper with gradlew build .

Notice any difference in our directory structure now?

how to write gradle task

We’ve got a new directory build . That’s where Gradle creates files during the build process, including compiled classes.

how to write gradle task

Taking a look inside build , we have a classes/java/main directory which contains the package structure with the compiled GradleTutorial.class file. Cool, so Gradle did what we wanted it to!

In the build/libs directory Gradle has also created a jar file for us. This jar contains the compiled class, which in theory we could go ahead and execute.

Let’s try that by running java -jar build/libs/gradle-tutorial.jar .

OK, so we got a big fat error saying no main manifest attribute. That just means that Java doesn’t know which class inside the jar file to run. Yes I know, there’s only one class to choose from, but that’s Java for you!

12. Configuring tasks #

We can easily fix this error in Gradle by configuring our project to add a Main-Class attribute to the jar file’s manifest file, telling Java what class to run. To understand how,  you need to know about another task that gets added to our project by the Java plugin, called jar .

how to write gradle task

The jar task is, unsurprisingly, responsible for creating the jar file and gets executed automatically when we run the build task.

The way we add the Main-Class manifest attribute is by configuring this jar task. 

To configure it we call a method jar , then manifest , then attributes , passing it a map. The values of the map are the additional manifest attributes, in this case it’s a key of Main-Class and a value of the fully qualified class name, com.tomgregory.GradleTutorial .

Add the above code to build.gradle , after plugins .

Now Gradle knows a bit more about how to build our jar file, so we need to run the build task again to regenerate the jar , using gradlew build . The new jar should now contain the extra manifest attribute, so let’s execute it again with the java command.

That’s great, it’s all working now! But before wrapping up this tutorial, there are two important aspects to cover that will be essential to working in any Gradle Java project.

13. Testing #

Imagine we want to write a quick test for our application, just to make sure it executes without throwing any exceptions. In Gradle, tests go into src/test/java , so let’s create the directory structure, then the same package structure com.tomgregory .

Within here create a source file, and inside add this test class which uses the JUnit 4 library.

In the test class, we have a single test case annotated with @Test which checks that the GradleTutorial.main method gets executed without throwing an exception. If you’re not familiar with JUnit, don’t worry because what’s important is to understand the process of running the test with Gradle.

Note that we have an import statement at the top of the file for org.junit.Test . The JUnit 4 library doesn’t come with Java, so we’ll have to add it separately as a dependency for Gradle to download and include on the Java classpath when our test is compiled and run.

14. Adding dependencies and repositories #

We specify dependencies in our build script by calling the dependencies method with a closure. Within that we call the testImplementation method, passing it a map containing the dependency’s group , name , and version .

Add the following to the end of build.gradle .

I found the latest version of JUnit 4 from .

Anything you pass to the testImplementation method will end up on the test compile and runtime classpaths. This means we’ll be able to compile and run the test which has a reference to the JUnit 4 library.

Declaring repositories #

Remember earlier when I said that Gradle automatically pulls dependencies from the internet?

Before it can do that, we need to tell it which repository to pull JUnit 4 from, which is the Central Maven repository. We do that in the build script by calling repositories with a closure, and then calling the mavenCentral method.

Add the following to build.gradle , just before dependencies .

We have to use round brackets () in this case to call mavenCentral because in Groovy you can only leave out brackets if the method has one or more parameters.

Let’s run the build task again with gradlew build . Remember from the build task’s description that it assembles and tests the project.

When Gradle executes the task it very briefly shows that it’s running the test, but so quickly you’ll likely miss it.

Fortunately, we can consult a test report generated in build/reports/tests/test . Open the index.html file in a browser and we see that 1 test was executed with 0 failures. Awesome!

how to write gradle task

15. Summary #

You’ve just seen how to apply the Java plugin to a Gradle project, letting you compile Java code with the build task. The build task also generated a jar file, which we configured to include a Main-Class manifest attribute in order to execute it.

Finally, we configured the repositories and dependencies to include JUnit 4 for tests, and got Gradle to successfully execute our test case.

For your reference, here’s the complete build script for the gradle-tutorial project.

You can also clone the accompanying GitHub repository which contains the same code.

16. Next steps #

If you were a complete Gradle beginner when you started watching this tutorial, then congratulations on taking your first steps with this build tool! You’ve now got a good idea why build tools are helpful for building Java applications, why Gradle is a good candidate for such a build tool, and how you can use Gradle to build a simple Java application.

If you want to continue learning Gradle, then I invite you to take my free course, Get Going with Gradle . Whilst what you learnt in this tutorial was indispensable as a first introduction, the Get Going with Gradle course is the fastest way to a working knowledge of Gradle , where you’ll feel confident working with simple Gradle projects.

Specifically, it helps you:

understand the full Gradle project structure & Java project layout (production/test code, resources, etc.)

become proficient working with the essential build script components

interact effectively with projects by understanding all tasks added by the Java plugin and how they relate in the task graph

With a mix of theory and practical lessons, if you take this course you’ll join hundreds of other students who now have more confidence working with Gradle projects.

Stop reading Gradle articles like these

This article helps you fix a specific problem, but it doesn't teach you the Gradle fundamentals you need to really help your team succeed .

Instead, follow a step-by-step process that makes getting started with Gradle easy .

how to write gradle task

Download this Free Quick-Start Guide to building simple Java projects with Gradle.

  • Learn to create and build Java projects in Gradle.
  • Understand the Gradle fundamentals.

how to write gradle task

Gradle Tasks with Kotlin

Nimrod Dayan

Nimrod Dayan

Recently, I had the need to send a Slack message from our CI server during our Android app build. Since Android is built with Gradle and in my opinion Gradle is just pure awesomeness, I thought why not just have a task that does just that.

The first thing I did was to look for a pre-made solution in the form of a Gradle plugin. I found one, but it wasn’t flexible enough as I wanted it to be. So I decided to create my own custom task to do that and while I’m at it have it written in Kotlin (of course :P).

Project structure

Creating a custom Gradle task can be done in different ways . You can just write Groovy code in your build.gradle or make it a bit nicer and have it in a separate Gradle file, say slack.gradle , and apply it to your app’s build.gradle with apply from: 'slack.gradle' . But that would be Groovy and not Kotlin. Although there’s a Gradle Kotlin DSL work-in-progress, but after checking out the examples, I decided not to try it since it looks like it adds more code to build.gradle than it reduces and overall the DSL doesn’t look as nice as it looks in Groovy (just my opinion). I’ll definitely have another look when the DSL matures.

Another option is to make a standalone Gradle plugin project. That might have been my first choice, but I planned on having only one class that defines the custom task and less code is always better.

The last option is to have a folder called buildSrc in your project’s root folder and put everything there. This option felt like the way to go in this case.

Setting up Kotlin support

Surprisingly, I couldn’t find anything about how to hook up Kotlin with Gradle in the buildSrc setup. Most of the tutorials I found were talking about creating a Gradle plugin project with Kotlin and then there was the Gradle Kotlin DSL project, etc. Hence I decided to write my own tutorial.

First, create a folder called buildSrc in your project’s root. This folder is automatically detected by Gradle so you don’t need to configure it anywhere. Now create a build.gradle file inside buildSrc . We will use it to set up the Gradle Kotlin plugin and library dependencies that our custom task will use. In this case, I’m going to depend on okHttp to do the networking.

  • Note that we also have dependency on gradleApi() which is a built-in method in Gradle.

One you’re done with build.gradle , create folders src/main/kotlin inside buildSrc . Sync your project with Gradle in Android Studio (the little green icon) and let’s continue to the custom task class creation. After the sync, Android Studio has identified src/main/kotlin as a source folder so you can now create packages there. Create your package however you want, mine is going to be org.codepond.gradle.slack .

Writing the task class in Kotlin

Inside this package you created, create Kotlin class SlackTask.kt with the following code:

A few important things to notice here (marked in bold):

  • The class must be defined as open . Kotlin classes cannot be extended by default (similar to final class in Java) and if not set correctly, Gradle will try to proxy your class and fail the build.
  • We extend DefaultTask since well, it’s a Gradle task ;)
  • We annotate our entry method with @TaskAction so Gradle knows what to execute.
  • We declare the properties messageText and webhookUrl as lateinit var properties since these two properties are mandatory in the task spec and we don’t want any default values. Gradle will make sure that these properties are assigned when configuring the task. If we don’t set them, the build will fail saying that these properties were not set. If you want to have optional properties for your task, you can annotate them with @Optional annotation.
  • Now considering the code itself, we set up OkHttp with a logging interceptor that logs directly to Gradle debug level and then it’s just standard OkHttp POST request. You can use JSON marshalling library if you have a complex JSON, but for this example, it was easier to just write it by hand.
  • It’s important to notice that the request is executed synchronously with execute() instead of enqueue() . Otherwise if you do it async, the task will just complete with build successful without actually ever sending the request (or sending it, but not receiving the response since we’re not blocking the thread).

Using the custom task in build.gradle

Now to the last part. We’ve got the custom task class in place, now we need to use it in our build.gradle . To do that you have to include an import statement at the beginning of the build.gradle file.

This wasn’t so obvious since in the official Gradle docs, it says that all classes under buildSrc will be available directly in build.gradle , but at least according to my tests this was true only when the class was written in Groovy — and not in Kotlin .

In your build.gradle (doesn’t matter if it’s the root or the app/module specific one — wherever you’d like to define this task) add the following:

More info on Slack Incoming Webhooks and how to generate them here .

And now to run this task from command line type: ./gradlew helloSlack . If you’re experiencing issues making the request, remember we set up OkHttp logging interceptor output to Gradle debug level logger. To show the logs run the same command with -d e.g.: ./gradlew helloSlack -d .

There you have it, you’ve successfully written a custom Gradle task in Kotlin that doesn’t require you to have a separate Gradle plugin project setup. Everything in one project under Android Studio!

If you liked this article please like and follow me here and on twitter.

Nimrod Dayan

Written by Nimrod Dayan

Senior Software Engineer with more than a decade of professional experience specialized in Android ( )

Text to speech

Software Testing Help

How To Use Gradle To Build, Test And Deploy Projects

how to write gradle task

This Tutorial Covers how to use Gradle to create a Project and Write Tasks in Groovy and run Tasks with Gradle Wrapper Using both the IDE & Build Command:

Being contemporary developers, we need to know about certain terms like Shift-Left, DevOps, Continuous Integration (CI), Continuous Delivery (CD), etc.

In this tutorial, we will learn about Groovy and Gradle along with their use to create Gradle build tasks and build projects respectively. Groovy is a multi-faceted language – with concise, familiar, and easy to use the syntax for Java platform and it can be used to write build and automation tasks.

Gradle to Build, Test and Deploy Java Projects

This language glues well with Gradle, which is one of the popular tools used in integrating a developer’s workflow in a CI/CD pipeline.

This tutorial explains Gradle for Java developers. It includes details on how it works; how to use Gradle to build source code written in Java, for deployment on any platform.

It provides plugins for most of the IDE’s and makes it easier to deliver software faster. To follow us along the journey of learning the above-stated concepts, it will be great if you look at the repository of a sample project that we have created on Github.

Table of Contents:

System Requirements And Prerequisites

Write your first program in groovy – hello world, basics of groovy language, what is gradle, features and advantages of using gradle, build a gradle project, automate gradle build using git actions, was this helpful, recommended reading.

This section includes the step of installing an IDE – IntelliJ IDEA and Java Development Kit (JDK). The details on the basic concepts in the Groovy language to get ourselves to speed towards writing our first build task are explained with the help of a code snippet.

Install IntelliJ IDEA

Install an IDE (Integrated Development Environment) for creating the Java project. We use IntelliJ IDEA (Community Edition) for this tutorial. Please follow the respective links to download and install it on Windows/Mac/Linux.

Windows: Click here Mac: Click here Linux: Click here

Install And Setup JDK

Download JDK . One needs to sign up for a RedHat account to complete the step. Once it is downloaded, run the setup to install it on your Windows PC. Once it is installed, open the command prompt and run the below-given commands to check whether it is working or not.

The below commands can be used to know where the JDK is installed or not.

D:\softwaretestinghelp>where java D:\softwaretestinghelp>where javac


Now let us configure the installed JDK with our IDE. Open the Platform settings in IntelliJ IDEA and Add the JDK by following the steps shown below. Please remember that this JDK is applicable to all the projects that you will work on using this IDE.

Step 1: Add the downloaded JDK to SDK under platform settings as shown in the image.


Step 2: Update Project SDK in the project settings as shown in the images

Update Project SDK

After applying the configured settings, please build the project once using the small green hammer icon in the IDE.

Set Up An Example Project

There are two ways to start with the project. We may either download the project zip file from the Github project page and import it as a Gradle project in the Intellij IDEA, or Clone the project from the Github repository.

Steps to clone the project from Github are given below:

Open the IDE by double-clicking the shortcut icon on your desktop. Please close any existing project if already opened. Please remember that Git plugin is by default bundled with IntelliJ IDEA. Thus, please do not install it.

Step 1: On the Welcome Screen of the IDE click on Get from Version Control .

IntelliJ IDEA Welcome Screen

Step 2: Provide the Github repository URL and click on Clone.


Step 3: Click on Yes when the Checkout file prompt is shown.

Checkout file prompt

Step 4: Wait for the background process to finish and check the output.

check the output

Step 5: Click on the folded Project pane to look at the project structure in the explorer.

Folded Project pane

In the project, open the Gradle build file called build.gradle using the file explorer of your IDE and write the below-given code at the end of the file.

Now run the first task by clicking Run on the context menu of the play task icon and observe the output of the println inbuilt method of Groovy. We can use “CTRL+SHIFT+F10”   as well. (Please refer to the image below)

println inbuilt method of Groovy

The output should look something similar to the one shown above.

Now that you have learned how to create your first program in Groovy, we can accelerate and learn about the basics of the language. This section will cover concepts such as variable names, syntax, operators, methods/functions/Closures, etc.

We will also cover the concepts that are more relevant from the project perspective such as accessing the properties of a project and importing closures/functions written in another build.gradle file.

Observe the below-given code snippet and comments to learn about various concepts of the language. This code snippet is quite handy for a quick walkthrough and a revision on the concepts of Groovy.

In both the loops, notice that the list has a zero-based index. Further details are mentioned at Groovy .

Now let’s learn about Gradle and see how to run a task.

It is a build automation system. It supports building projects written in multiple languages. In this tutorial, we are using Java. This section explains the method of running Gradle commands from the command line. We are going to use it for building, testing, and deployment of our sample project.

Gradle Dependencies

You might already know how important it is to install dependencies in any open-source software project. Gradle can search for dependencies on public repositories such as Maven, Jcenter, and Google.

Mention these repositories in build.gradle file as shown below:

Now mention the compile-time dependencies as shown below.

The mentioned dependencies are automatically downloaded and included in the project’s CLASSPATH by the Gradle plugin. Check the downloaded dependencies in the project explorer of the IDE.


Check the Gradle version by using the below-given command.


Enlisted below are some of the features that help in easy standardization and adoption of Gradle as a part of DevOps in an organization.

  • It uses a DSL based language called Groovy. It is easier to write build tasks in Groovy than in XML. Moreover, XML’s are cumbersome and not easy to read. However, Groovy is easier to learn and read.
  • It supports creation builds for projects based on both monolithic and microservices architectures.
  • It can be used to create multiple artifacts such as Documents, API’s. implementation jars, etc. and publish them as part of the same build.
  • It has quite a powerful language construct to order the interdependent tasks as a part of the builds.

There are many more features that enable the teams to customize their builds while packaging the software with higher quality. More details on the features are given here .

Now let us move ahead and run a Gradle build task.

Run A Gradle Task

Run the command shown below under the project’s root directory to run the build task called task1.

D:\softwaretestinghelp\gitrepo>.\gradlew.bat task1

Check the output as shown below.


In this section, we will go through the project structure, understand its various components, and build the project.

Structure Of The Sample Project

The sample project under discussion has an src folder with two main directories (folders) viz. Main and test. The main directory has Java source code related to a sample command-line application called HelloWorld.

The HelloWorld class has two methods i.e. The main method, which prints the first argument out of the given list of arguments and a method1 method, which prints 1st argument concatenated with the first 3 characters of the second argument.

The test folder has a JUnit test class that has tests to test the above-mentioned methods in our Application. Please check the source code of these tests.

The sample project also has a Gradle wrapper folder. You must use the mentioned Gradle wrapper version while running your build tasks.

The Version of Gradle is very important and whenever developers want to share their code it is always beneficial to share a wrapper along with the project files. It saves a lot of time as wrapper automatically downloads the declared version of the Gradle.

Examples Of Build Tasks

Documenting the code is considered as one of the most important attributes of a developer. It is a usual practice to share the documentation in html format. Gradle helps in generating javadocs in html format projects. We can generate javadocs using the below command.

D:\softwaretestinghelp\gitrepo>.\gradlew.bat javadoc

Please check the javadoc under build directory in the project and you should see the results similar to the ones shown in the image below.


Please follow the  javadoc  style guide given at this link while writing Java documentation.

Now let’s change the build.gradle file to generate the documentation for test resources as well.

Update the build.gradle file with the snippet shown below

Again run the Gradle javadoc command to generate the documentation for main as well as test sources.

Constructor Summary

More details on the Gradle build tasks can be seen here .

Command to know more Gradle tasks is given below.

Gradle CommandLine All Tasks

Now let’s build the project.

Build The Gradle Project

Follow the below-mentioned steps, to build the sample project from the command line: 

  • Change the project path.
  • Use the below command to build the project.

However, you can also build the project by clicking the small hammer icon in the IDE.

The output of the build command will be as shown below.

output of the build command

Failures in the build run results are intentional for the purpose of this tutorial and can be neglected.

If you want to see the results of the tests that were run as part of this build, then you can check the reports folder as shown in the image below.

To check the results you can open the index.html file in a browser.


As developers, we have to set up our workflows to build, test, and publish our projects, in order to collaborate with the operations team.

Moreover, setting up an environment by ourselves can be a daunting task and might have repercussions on our productivity. With the advent of a new culture of DevOps, we need to automate our workflows to reduce the challenges, arising out of build failures.

Meanwhile, software projects with developers, who are geographically distributed, need collaboration with the help of SCM software such as Git.

Thanks to Github Actions. Now you can see an additional tab on any Github repository that you create. You can create your development workflows and run them on any Github event such as push, release, pull_request, etc. This is revolutionary in terms of giving the power of CI/CD to the developer-community.

Open the Git Actions configurations at .github/workflows/gradle.yml file in the project. Notice that we are developing our project on Windows and in Git Actions we are testing it on ubuntu_latest.


Github Actions also has community-powered workflows that we can leverage on and increase the speed of delivering your project to customers. Based on the status of your build you can decide whether to release the project or not. We have given the example of a pre-release of the repository of the sample project.

An Optional Exercise

Given below are some of the steps for you to try.

  • Create a new repository in Github.
  • Add a reference of the new remote in the gradle_sample project.
  • Use the commands to publish the changes to the new repository.
  • Observe the results for your Gradle build under Git Actions.

Gradle is being used by teams in companies such as LinkedIn, Adobe, Netflix, etc. and it is a great tool to master. Working with Gradle is much easier than working in other build tools such as Maven and Ant.

These days it is all about speed and agility. Learning Gradle and Groovy can help you in adopting DevOps principles more easily.

To summarize, we covered concepts on the creation of a Gradle project, on writing build tasks in Groovy and on running tasks with Gradle wrapper during development using both the IDE and Gradle build command.

We also tested the build on a different target platform such as ubuntu_latest. We can use it with a build status, that can help in making a decision related to a project release.

If you are an automation engineer using Selenium Webdriver, then don’t fail to read our upcoming tutorial on configuring and setting up a Selenium project with Gradle.

  • Gradle Vs Maven And Maven Plugins
  • How To Create Gradle Project With Selenium
  • Spock Tutorial: Testing With Spock And Groovy
  • How to Write Basic Groovy Script in SoapUI - SoapUi Tutorial #6
  • How to Use Properties in SoapUI Groovy Script - SoapUI Tutorial #7
  • Learn Advanced SoapUI Groovy Scripting Concepts - SoapUI Tutorial #9
  • How to Handle Exception in SoapUI Groovy Scripts – SoapUI Tutorial #11
  • Use of Maven Build Automation Tool and Maven Project Setup for Selenium - Selenium Tutorial #24

Leave a Comment Cancel reply

IntelliJ IDEA 2024.1 Help

Gradle tasks.

A Gradle task is a small piece of work that is performed in the Gradle build cycle. For more information on the task concept, see the Gradle documentation .

IntelliJ IDEA lets you run, debug and manage Gradle tasks in your project.

Run Gradle tasks

You can use several ways to run Gradle tasks such as run them from the Run Anything window, with a run configuration , from a context menu, and even run several tasks with one run configuration.

Run a Gradle task in the Run Anything window

In the Run Anything window, start typing a name of the task you want to execute. To execute several tasks, enter task names using space to separate each new task. Alternatively, scroll down to the Gradle tasks section and select the task you need. Press Enter .

Enter a task name

If you have linked projects and want to run a task for the specified project then in the Run Anything window, in the top-right corner, from the Project list, select the name of the project and in the search field enter the name of your task.

IntelliJ IDEA runs the specified task and displays the result in the Run tool window.

Run tool window: Gradle task

IntelliJ IDEA also saves the task in the Run Anything window under the Recent section as well as under the Run Configurations node in the Gradle tool window.

Run Anything: Recent

Run a Gradle task via Run Configurations

You can add some additional parameters to your task, configure it as a run configuration , save it and use that run configuration in your project whenever you need.

Open the Gradle tool window.

Right-click the task for which you want to create the Run configuration.

From the context menu select Modify Run Configuration .

Create the task run configuration

In Create Run Configuration: 'task name' , you can use the default settings or configure the additional options and click OK .

Run Configuration for a Gradle task

IntelliJ IDEA displays the task under the Run Configurations node.

Gradle tool window: Run Configurations

Double-click the task to run it or right-click the task and from the context menu select Run .

Run Configurations: the context menu

Run a Gradle task from the context menu

Right-click a task that you want to run.

From the context menu select Run 'task name' .

Gradle tool window: the context menu

Run several Gradle tasks simultaneously

You can create a run configuration for several tasks.

Select Run | Edit Configurations Alt+Shift+F10 .

The Run/Debug Configurations dialog opens.

Add new Gradle run/debug configuration

On the right side of the Run/Debug Configurations dialog, in the Name field, enter the name of your configuration. Also, you can specify where you want to run your configuration. Use the Run on drop-down list to specify the run target option.

Use the Run section to specify settings for the run configuration.

As an example, check the following settings:

For example, specify clean and build , and add the argument --debug .

If you want to add VM options , click the Modify options link and in the dialog that opens, under Java section, select Add VM options . The VM options field is added to the run configuration, and you can specify the needed parameters. For example, specify -Xmx3g .

Gradle Run/Debug configuration

For more information about run configurations, refer to Run/debug configurations .

The created configuration is added to the Run Configurations node in the Gradle Projects tool window.

Double-click the configuration to run the task or right-click the configuration and select Run .

Gradle tool window: run configuration

Debug Gradle tasks and scripts

You can debug Gradle tasks and scripts the same way you debug your regular applications.

IntelliJ IDEA opens one tab per debugging session for Gradle scripts and for your regular tests. The Debug tool window contains Frames and Variables , as well as the Console output.

Debug tool window

You can perform stepping actions and stop on breakpoints that you set in build.gradle and in the regular test classes under a single tab in the debugging session.

Stepping through the breakpoints

Configure Gradle debugging process

Create a run/debug configuration . If you have the existing run/debug configuration, select it from the main menu, and click Edit Configurations .

On the Run/Debug Configurations page, click the Gradle Debug tab.

Use the following options to configure the Gradle debugging process:

Debug Gradle scripts :

this option is disabled when you execute your test using left gutter in the editor or the context menu. This is done to speed up your debugging process.

Debug forked Gradle tasks in separate debug tabs : when this option is selected any new debugging process is run under the different tab in the Debug tool window. By default, this option is disabled and the debugging process is performed under the same tab.

Debug all tasks on the execution graph : when you select this option, every task in the execution graph will be debugged. For example, all the dependent tasks of the task you are trying to debug will be debugged as well.

Debug a Gradle script task

Open your build.gradle in the editor.

Debug build script

IntelliJ IDEA starts the debugging session, and you can check the results in the Debug tool window.

Debug tool window

Debug a Gradle task

Use the Gradle tool window to debug Gradle tasks that implement the org.gradle.process.JavaForkOptions interface, for example, test or run .

In the Gradle tool window, click the project, open the Tasks node, and right-click a task you want to debug.

From the context menu, select Debug .

The debugging process is started and the task is added to the list of the recent tasks located under the Run Configurations node.

Assign a shortcut to a Gradle task

IntelliJ IDEA lets you assign shortcuts to Gradle tasks and execute those tasks with a single key. You can also assign a shortcut to the Gradle run/debug configuration that can contain more than one task.

In the Gradle tool window, right-click the desired task.

From the context menu, choose Assign Shortcut .

Gradle tool window: Assign Shortcut

The Keymap dialog opens.

In the Keymap dialog, under the Gradle node navigate to your task.

Right-click the task and from the list that opens, select a type of the shortcut you want to assign.

Add a shortcut

In the dialog that opens, depending on the shortcut's type, configure your shortcut and click OK .

In our case let's add a keyboard shortcut.

Keyboard shortcut dialog

You can see that the shortcut is displayed against your task in the Gradle tool window.

Gradle tool window: displayed shortcut

While in the Keymap dialog, you can add a new task to which you want to assign a shortcut.

In the Keymap dialog, under the Gradle node, click Choose a task to assign a shortcut .

Keymap dialog: Choose a task to assign a shortcut

In the dialog that opens, select a task you need and click OK .

Choose Gradle task dialog

The task is added to the list under the Gradle node. Now you can configure the shortcut .

Configure running triggers for Gradle tasks

IntelliJ IDEA lets you run Gradle tasks before your project's execution or set other conditions using the task activation configuration.

In the Gradle tool window, right-click a Gradle project.

From the context menu, select Tasks Activation .

On the Choose activation phase menu, choose when to run your task, for example, Before Build , After Sync , and so on.

On the Choose task menu, select the actual task.

The task and activation phase will be added to the list in the Task Activation dialog. You can also see the activation phase name against the selected task in the Gradle tool window.

Alternatively, you can select the activation phase name from the context menu when you right-click the task you want to execute in the Gradle tool window.

You can also create a run/debug configuration that would depend on a Gradle task.

In the main menu, go to Run | Edit Configurations to open the run/debug configuration for your project.

In the list that opens, select Run Gradle task .

In the Select Gradle Task dialog, specify the project and the task that you want to execute before launching the project. You can specify a Gradle linked project or any other Gradle project. Note that if your Gradle project is not linked then IntelliJ IDEA will use the default configurations (for example, a bundled Gradle version) to run the task.

Using Cucumber with Gradle

Last updated: January 8, 2024

how to write gradle task

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page .

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page .

Whether you're just starting out or have years of experience, Spring Boot is obviously a great choice for building a web application.

Jmix builds on this highly powerful and mature Boot stack, allowing devs to build and deliver full-stack web applications without having to code the frontend. Quite flexibly as well, from simple web GUI CRUD applications to complex enterprise solutions.

Concretely, The Jmix Platform includes a framework built on top of Spring Boot, JPA, and Vaadin , and comes with Jmix Studio, an IntelliJ IDEA plugin equipped with a suite of developer productivity tools.

The platform comes with interconnected out-of-the-box add-ons for report generation, BPM, maps, instant web app generation from a DB, and quite a bit more:

>> Become an efficient full-stack developer with Jmix

Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.

Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.

Write code that works the way you meant it to:

>> CodiumAI. Meaningful Code Tests for Busy Devs

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .

The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

>> Take a look at DBSchema

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only , so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server , hit the record button, and you'll have results within minutes:

>> Try out the Profiler

Do JSON right with Jackson

Download the E-book

Get the most out of the Apache HTTP Client

Get Started with Apache Maven:

Working on getting your persistence layer right with Spring?

Explore the eBook

Building a REST API with Spring?

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> REST With Spring (new)

Get started with Spring and Spring Boot, through the reference Learn Spring course:


The AI Assistant to boost Boost your productivity writing unit tests - Machinet AI .

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code. And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.

Simplify Your Coding Journey with Machinet AI :

>> Install Machinet AI in your IntelliJ

Looking for the ideal Linux distro for running modern Spring apps in the cloud?

Meet Alpaquita Linux : lightweight, secure, and powerful enough to handle heavy workloads.

This distro is specifically designed for running Java apps . It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.

Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:

>> Try Alpaquita Containers now.

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .

You can explore the course here:

>> Learn Spring Security

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot .

Get started with Spring Data JPA through the guided reference course:


Get started with Spring Boot and with core Spring, through the Learn Spring course:

1. Introduction

Cucumber is a test automation tool that supports Behavior-Driven Development (BDD). It runs specifications written in plain text Gherkin syntax that describes the system behavior.

In this tutorial, we’ll see a few ways to integrate Cucumber with Gradle in order to run BDD specifications as part of the project build.

First, let’s set up a Gradle project, using Gradle Wrapper .

Next, we’ll add the cucumber-java dependency to build.gradle :

This adds the official Cucumber Java implementation to our project.

3. Running Using Custom Task

In order to run our specifications using Gradle, we’ll create a task that uses the Command-Line Interface Runner (CLI) from Cucumber .

3.1. Configuration

Let’s start by adding the required configuration to the project’s  build.gradle file:

Next, we’ll create the custom  cucumberCli task:

This task is configured to run all the test scenarios found in .feature files under the  src/test/resources  directory.

The –glue option to the Main class specifies the location of the step definition files required for running the scenarios.

The –plugin option specifies the format and location of the test reports. We can combine several values to generate the report(s) in the required format(s), such as pretty and HTML , as in our example.

There are several other options available. For example, there are options to filter tests based on names and tags.

3.2. Scenario

Now, let’s create a simple scenario for our application in the src/test/resources/features/account_credited.feature file:

Next, we’ll implement the corresponding step definitions — the glue — required for running the scenario:

3.3. Run the Task

Finally, let’s run our  cucumberCli task from the command line:

As we can see, our specification has been integrated with Gradle, runs successfully, and the output is shown on the console. Also, the HTML test report is available in the specified location.

4. Running Using JUnit

Instead of creating the custom task in Gradle, we can use JUnit to run the cucumber scenarios.

Let’s start by including the cucumber-junit  dependency:

As we’re using JUnit 5, we also need to add the junit-vintage-engine dependency:

Next, we’ll create an empty runner class in the test sources location:

Here, we’ve used the JUnit Cucumber runner in the  @RunWith annotation. Furthermore, all the CLI runner options, such as features and plugin , are available via the @CucumberOptions annotation.

Now, executing the standard Gradle test  task will find and run all the feature tests , in addition to any other unit tests:

5. Running Using Plugin

The last approach is to use a third-party plugin that provides the ability to run specifications from the Gradle build.

In our example, we’ll use the  gradle-cucumber-runner plugin for running Cucumber JVM. Under the hood, this forwards all calls to the CLI runner that we used earlier. Let’s include it in our project:

This adds a cucumber task to our build, and now we can run it with default settings:

It’s worth noting that this is not an official Cucumber plugin , and there are others also available that provide similar functionality.

6. Conclusion

In this article, we demonstrated several ways to configure and run BDD specifications using Gradle.

Initially, we looked at how to create a custom task utilizing the CLI runner. Then, we looked at using the Cucumber JUnit runner to execute the specifications using the existing Gradle task. Finally, we used a third-party plugin to run Cucumber without creating our own custom tasks.

As always, the full source can be found over on GitHub .

Slow MySQL query performance is all too common. Of course it is.

The Jet Profiler was built entirely for MySQL , so it's fine-tuned for it and does advanced everything with relaly minimal impact and no server changes.

Just published a new writeup on how to run a standard Java/Boot application as a Docker container, using the Liberica JDK on top of Alpaquita Linux:

>> Spring Boot Application on Liberica Runtime Container.

Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:

Basically, write code that works the way you meant it to.

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.

Build your API with SPRING - book cover

Part 2: Running Gradle Tasks

Step 0. before you begin, step 1. viewing available tasks, step 2. understanding tasks, step 3. understanding dependencies between tasks, step 4. viewing tasks in the ide, step 5. running tasks in the ide, step 6. running tasks in the terminal.

Learn the basics of Gradle tasks by running one and looking at its output.

In this section you will:

See available tasks

Run a task and inspect the results

Understand tasks

Explore task dependencies

You initialized your Java app in part 1 .

A task is a basic unit of work that can be done by Gradle as part of the build.

In the tutorial directory, enter the command below to list all the available tasks in the project:

The list includes tasks contributed by the application plugin and the plugin it applies:

A task might be responsible for compilation, copying, and moving files around, creating JAR files, generating Javadoc, publishing artifacts to repositories, or many other discrete units of work.

You can also list the tasks only available in the app subproject by running ./gradlew :app:tasks .

You can obtain more information in the task listing using the option: .

In part 1 of the tutorial, we ran the build task using the ./gradlew build command.

We’ve listed the tasks available when the project is initialized, but what if we want to create our own tasks?

Gradle provides many built-in tasks that developers can use to enhance build scripts.

This example task copies *.war files from the source directory to the target directory using the Copy built-in task.

This task, if added to build.gradle(.kts) file in the app subproject directory, would be executed using the command ./gradlew :app:copyTask .

Popular built-in tasks include:

Copy - Copy is useful to copy files around.

Delete - Delete is useful to delete files and directories.

Exec - Exec is useful to execute arbitrary O/S commands.

Zip - Zip is useful to bundle files.

With many more documented in the Kotlin and Groovy DSLs.

Many times, a task requires another task to run first. If task B uses the output of task A, then task A must complete before task B begins.

A task may declare its dependencies explicitly.

A task may depend on other tasks implicitly.

Here is an example of explicit task dependency:

In this case, hello prints before greet . The output is Hello! How are you? .

Task execution order is automatically determined by Gradle, taking into account explicit and implicit task dependencies. If there is no dependency between tasks, Gradle enables users to request a specific execution order.

Project tasks are also available in IntelliJ. The project should be open following part 1 of the tutorial.

On the right-hand side of your window, open the Gradle pane:

intellij idea tasks

You can run a Gradle task via IntelliJ by double-clicking that task in the pane.

Double-click tutorial > app > build > build .

intellij idea build

Once the build finishes, make sure it is successful in the IntelliJ console:

Run the following command in your terminal:

The build task uses the source code and its dependencies to build the app. As seen in the output, the build task compiles, assembles, tests, and checks the code.

The tasks are printed in order of execution. The jar tasks is a dependency of the build task.

The jar task creates an executable JAR file of the app. Let’s run it by itself:

As expected, the compileJava task is a dependency of the jar task and executed first. Once the task finishes, an app.jar file is created in your tutorial/app/build/libs/ folder.

Invoke the run task and check the output:

The run task executes the code in tutorial/app/src/main/java/com.gradle.tutorial/ . The Java code in simply prints "Hello World" to the screen:

Next Step: Dependency Management >>

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

1 Java Project Manager, is a Maven/Gradle alternative with a twist. Its a single Java file itself, which should be edited by you to configure your project.


Folders and files.

23 Commits
workflows workflows
main/java main/java

Repository files navigation

1 Java Project Manager (1JPM), is a Maven/Gradle alternative with a twist. It's a single Java file itself, which should be edited by you to configure your project.

Meaning instead of writing XML (Maven) or Groovy (Gradle), your build file is Java code too. Thus to build your project, download/copy the file into your project, open a terminal and execute:

  • Java 11 and above: java jar
  • Java 8 to 10: javac && java -cp . JPM jar
  • Earlier Java versions are not supported

jar is a task, which compiles and creates a jar file from your code. If you want to include dependencies in the jar run fatJar instead.

1JPM works in a very similar way to Gradle, however everything in 1JPM is a plugin (even all its tasks), and third-party plugins can be added simply by appending their Java code inside ThirdPartyPlugins (these must be written in Java 8 and not use external dependencies).

Why a single file?

  • IDEs should provide decent auto-complete when is in the project root (where your pom.xml/build.gradle) usually is.
  • To access all your IDEs fancy features, you can also add to ./src/main/java. This also grants the rest of your project easy access to its data, like your projects version for example. Just make sure that your working dir is still at ./ when executing tasks.
  • Simple drag and drop installation.
  • Direct access to the source of 1JPM and what happens under the hood for those who like exploring or better understanding how something works, which can be helpful if issues arise.

Cons / Todo

  • Developing plugins is tricky since you can't really use third-party dependencies at the moment. A workaround for this would be developing a task like "minifyProject" which would merge a complete project into 1 line of code, including any dependencies used.

1JPM is a new project and currently an early-access/beta release, thus does not contain all the functionalities of the other major build tools like Maven and Gradle, however should provide the basic and most used functions.

IntelliJ IDEA and VSCode plugins (Future release)

  • Allow seamless integration into major IDEs.

Below you can see some Gradle tasks that are available in 1JPM (or planned).

  • clean : ✅ Deletes the build directory.
  • Sub-task: compileJava.options.compilerArgs : ✅ Configures Java compiler arguments.
  • Sub-task: processResources.expand( : ✅ Expands placeholders in resource files.
  • classes : ✅ Assembles the compiled classes (depends on compileJava and processResources ).
  • compileTestJava : Compiles test Java source files.
  • processTestResources : Processes test resource files.
  • testClasses : Assembles the compiled test classes (depends on compileTestJava and processTestResources ).
  • Sub-task: test.useJUnitPlatform() : Configures JUnit Platform for testing.
  • Sub-task: jar.manifest : ✅ Configures the JAR manifest.
  • javadoc : Generates Javadoc for the main source code.
  • assemble : ✅ Assembles the outputs of the project (depends on classes and jar ).
  • check : Runs all checks (depends on test ).
  • build : ✅ Aggregates all tasks needed to build the project (depends on assemble and check ).
  • cleanTask : Deletes the output of a specific task (e.g., cleanJar , cleanTest ).

test (Future release)

  • testClasses : Assembles the compiled test classes.
  • Sub-task: test.include : Specifies which test classes to run.
  • Sub-task: test.exclude : Specifies which test classes to exclude.
  • integrationTest : Runs integration tests (custom task, needs configuration).
  • compileJava : ✅ Compiles Java source files.
  • processResources : ✅ Processes resource files.
  • classes : ✅ Assembles the compiled classes.
  • jar : ✅ Assembles the JAR file.
  • fatJar : ✅ Creates a fat JAR with all dependencies (requires Shadow plugin).
  • assemble : ✅ Aggregates classes and jar tasks.

check (Future release)

  • test : Runs the unit tests.
  • checkstyle : Runs Checkstyle for code style checks (requires Checkstyle plugin).
  • pmdMain : Runs PMD for static code analysis (requires PMD plugin).
  • spotbugsMain : Runs SpotBugs for bug detection (requires SpotBugs plugin).
  • check : Aggregates all verification tasks, including test , checkstyle , pmdMain , and spotbugsMain .

dependencies ✅

  • dependencies : ✅ Displays the dependencies of the project.
  • dependencyInsight : Shows insight into a specific dependency.
  • dependencyUpdates : ✅ Checks for dependency updates.
  • help : ✅ Displays help information about the available tasks and command-line options.
  • components : Displays the components produced by the project.
  • tasks : ✅ Lists the tasks in the project.
  • tasks --all : Lists all tasks, including task dependencies.
  • Sub-task: jar.manifest.attributes : Sets manifest attributes.
  • Sub-task: jar.from : Includes additional files in the JAR.

publish (Future release)

  • generatePomFileForMavenPublication : Generates the POM file for Maven publication.
  • publishMavenPublicationToMavenLocal : Publishes to the local Maven repository.
  • publishMavenPublicationToMavenRepository : Publishes to a remote Maven repository.
  • publish : Aggregates all publishing tasks.

eclipse (Future release)

  • eclipseClasspath : Generates the Eclipse classpath file.
  • eclipseJdt : Generates the Eclipse JDT settings.
  • eclipseProject : Generates the Eclipse project file.
  • eclipse : Aggregates all Eclipse tasks.

idea (Future release)

  • ideaModule : Generates the IntelliJ IDEA module files.
  • ideaProject : Generates the IntelliJ IDEA project file.
  • ideaWorkspace : Generates the IntelliJ IDEA workspace file.
  • idea : Aggregates all IDEA tasks.

run (Future release)

  • compileJava : Compiles Java source files.
  • processResources : Processes resource files.
  • classes : Assembles the compiled classes.
  • Sub-task: run.main : Specifies the main class to run.
  • Sub-task: run.args : Specifies command-line arguments.
  • Java 100.0%
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Gradle publish to remote repository is not enabled

I'm trying to publish a java package using gradle. Everything builds and tests correctly but when i try to run the publish task i get the following error:

I can't find any references to that error message in Google. How do i enable publishing to remote repositories?

This is my build.gradle file:

I get the same error with and without the publishing section

Carlos Rodriguez's user avatar

  • Not sure if it has any effect: Afaik, if you have more than one repository [of the same type] you shall give them names via the name property inside the maven { ... } enclosure. If it does not help, I'd recommend to check your gradle.settings file and to check whether there is an init.gradle file in ~/.gradle . I could imagine if this publishing is configured somewhere, it is in the settings or init scripts. –  Max M Commented 11 hours ago
  • Have to revise: The repository names are neither obligatory nor is there any recommendation from gradle. Don't know where this point rose in my head. But I'd still recommed to check the project gradle.settings and init.gradle scripts in GRADLE_USER_HOME . –  Max M Commented 10 hours ago
  • I cannot reproduce this. I created a new project with gradle init (Gradle 8.8), copied your plugin id 'maven-publish' and the publishing block into the build script, and added quotes around the password. When I run ./gradlew publish it says "Could not write to resource ' xxxxxxxxxxxxxxxxxx/xxxxxxxxx/xxxxxx/xxxxx/xxxxxx-xxxxx.jar' ." So it does try to run the publishing action. Maybe your minimal reproducible example isn't that complete. I'd check for other configuration options that get in the way, like @MaxM said. –  Robert Commented 2 hours ago

Know someone who can answer? Share a link to this question via email , Twitter , or Facebook .

Your answer.

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Browse other questions tagged java gradle or ask your own question .

  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Meaning of output from fast-chess engine testing suite
  • How do i get a new poetry line to be hanging indented .25 inches yet in a custom blockquote format ,5 inches away from margins?
  • As a DM, what should I do if a person decides to play a rogue?
  • Is it a security issue to expose PII on any publically accessible URL?
  • What scientifically plausible apocalypse scenario, if any, meets my criteria?
  • Power pedals on a fully MTB (riding flat roads), later on road/gravel bike
  • Could a Black Market exist in a cashless society (digital currency)?
  • Are there any reasons I shouldn't remove this odd nook from a basement room?
  • Good postdoc position, but how to approach advisor about feelings of self-doubt?
  • I cannot get Pgfplots to display all my axis labels
  • Accommodating whiteboard glare for low-vision student
  • Keyboard Ping Pong
  • Is it possible to go back to the U.S. after overstaying as a child?
  • Using grout that had hardened in the bag
  • Can a MicroSD card help speed up my Mini PC?
  • French Election 2024 - seat share based on first round only
  • Questions about writing a Linear Algebra textbook, with Earth Science applications
  • Linux disk space running full
  • How can I explain the difference in accuracies in different ML models?
  • Where do we go if we gain knowledge of the absolute truth?
  • Error concerning projectile motion in respected textbook?
  • How to delete an island whose min x less than -1
  • Why do "dual frequency" or low frequency switching regulators exist when higher frequency is better?
  • Crazy emails from superstar professor

how to write gradle task


  1. Example task graphs

    how to write gradle task

  2. Gradle tasks

    how to write gradle task

  3. Write your first Gradle build script to start automating your project

    how to write gradle task

  4. Gradle tasks

    how to write gradle task

  5. The Gradle build system- Tutorial

    how to write gradle task

  6. Build Tool: Gradle

    how to write gradle task


  1. Creating the Project With Gradle and Adding all Dependencies

  2. Gradle Tutorial # 7 : What are Gradle tasks [Gradle tasks in build.gradle ]

  3. Gradle tutorial # 10 : Copy task in gradle [ Typed Tasks]

  4. ✅ gradle:compileGroovy 100% Solution

  5. Gradle task assembleDebug failed with exit code 1 flutter in android studio

  6. Tiled Terrain Sets and Gradle task to autogenerate enums


  1. Writing Tasks

    However, the generic DefaultTask provides no action for Gradle. If users want to extend the capabilities of Gradle and their build script, they must either use a built-in task or create a custom task:

  2. Advanced Tasks

    Learn how to develop custom Gradle task types with advanced features and best practices. Kotlin and Groovy examples included.

  3. Gradle Custom Task

    In this article, we'll cover how to create a custom task in Gradle. We'll show a new task definition using a build script or a custom task type.

  4. Using Tasks

    A task represents some independent unit of work that a build performs. This might be compiling some classes, creating a JAR, generating Javadoc, or publishing some archives to a repository. When a user runs ./gradlew build in the command line, Gradle will execute the build task along with any other tasks it depends on.

  5. Creating Custom Gradle Tasks for Java Developers

    Learn how to create custom Gradle tasks for your Java project with this practical guide. Improve your workflow and productivity today!

  6. Gradle Task Inputs and Outputs

    Declaring Gradle task inputs and outputs is essential for your build to work properly. By telling Gradle what files or properties your task consumes and produces, the incremental build feature kicks in, improving the performance of your build. You'll also be following best practices, allowing you to easily create more complex projects. In this article, you'll learn how Gradle task inputs ...

  7. Understanding Gradle Tasks

    Learn how to create, use, and see the outcomes of tasks, and more

  8. All about the Gradle task graph

    The task graph means you only need to run the task you care about, and any other required tasks get run automatically. In this article, you'll learn all about the Gradle task graph, how to add tasks to it, and how to print it out. Tasks and task dependencies A Gradle task is a unit of work which needs to get done in your build.

  9. Gradle custom task which runs multiple tasks

    I wanna run multiple gradle tasks as one. So instead of ./gradlew clean build publish I want to have a custom task ./gradlew cleanBuildPublish that executes clean build and publish in order. ...

  10. Gradle Tutorial for Complete Beginners

    Gradle tasks are individual build actions you can run from the command line. You might have a task to compile your Java code, a task to test the code, and a task to package the compiled classes into a jar file. We saw a list of all the available tasks earlier when we ran gradlew tasks.

  11. The Comprehensive Guide to Gradle: Dive Deep with Examples

    In Gradle, everything is either a project or a task. A project represents a library, application, or even a set of shared tasks or configurations, while a task represents an atomic unit of work.

  12. Gradle Tasks with Kotlin. Write custom Gradle tasks classes in…

    Creating a custom Gradle task can be done in different ways. You can just write Groovy code in your build.gradle or make it a bit nicer and have it in a separate Gradle file, say slack.gradle, and ...

  13. Writing Build Scripts

    Gradle scripts are written in either Groovy DSL or Kotlin DSL (domain-specific language). A build script configures a project and is associated with an object of type Project. As the build script executes, it configures Project. The build script is either a *.gradle file in Groovy or a *.gradle.kts file in Kotlin.

  14. Gradle

    Step-by-step lessons on how to use Gradle, both in general and for specific tasks.

  15. How To Use Gradle To Build, Test And Deploy Projects

    This tutorial covers how to use Gradle to create a Gradle Project, Write Tasks in Groovy & run them with Gradle Wrapper Using both the IDE & Build Command.

  16. Gradle tasks

    IntelliJ IDEA lets you run Gradle tasks before your project's execution or set other conditions using the task activation configuration. In the Gradle tool window, right-click a Gradle project. From the context menu, select Tasks Activation. In the Tasks Activation dialog, click .

  17. Writing Custom Gradle Plugins

    A quick and practical example of writing a custom Gradle plugin.

  18. Understanding Tasks

    tasks - Displays the tasks runnable from project ':app'. We observe that only a small number of help tasks are available at the moment. This is because the core of Gradle only provides tasks that analyze your build. Other tasks, such as the those that build your project or compile your code, are added by plugins.

  19. Using Cucumber with Gradle

    Initially, we looked at how to create a custom task utilizing the CLI runner. Then, we looked at using the Cucumber JUnit runner to execute the specifications using the existing Gradle task. Finally, we used a third-party plugin to run Cucumber without creating our own custom tasks.

  20. Part 2: Running Gradle Tasks

    A task is a basic unit of work that can be done by Gradle as part of the build. In the tutorial directory, enter the command below to list all the available tasks in the project:

  21. Configure a Gradle Task at Runtime

    println(File("sha.txt").readText()) Ideally, you should create a custom task type specifying the input file and also specifying the output file so that Gradle can cache tasks inputs/outputs. Refer to Incremental tasks for more details. Thanks for the answer, I did in fact just end up writing a custom task though.

  22. GitHub

    1 Java Project Manager (1JPM), is a Maven/Gradle alternative with a twist. It's a single Java file itself, which should be edited by you to configure your project. Meaning instead of writing XML (Maven) or Groovy (Gradle), your build file is Java code too.

  23. Gradle publish to remote repository is not enabled

    I'm trying to publish a java package using gradle. Everything builds and tests correctly but when i try to run the publish task i get the following error: FAILURE: Build failed with an exception. ...