How to write a custom gradle task, which calls another gradle task

I have a requirement, where I like to write a custom gradle task (in my gradle plugin). This task accept a parameter as gradle taskname.

Examle: gradle executeGradleTask -PgradleTaskName=“some-gradle-task”

It first checks if ‘some-gradle-task’ is a valid task

  • If yes then execute the task
  • Else print a message that task is not available.

Please suggest if gradle provide support for such a requirement. If yes, then how to implement the same.

It’s possible to do so using the internal “execute()” method.
But I wonder why you would do such thing.
The concept is that tasks depend on each other, and gradle figures out the tasks to execute and their order, based on the tasks asked during a build invocation.
Could you elaborate on your usage? Is it exactly your given example?


  • Single Hudson/Jenkins job is use for running build for different product release.
  • Now lets say that I have release 1.1, 1.2, 1.3 etc for my product
  • Now for release 1.4, I want to run one extra task sonarRunner
  • If I directly add this task to hudson/Jenkins job then if a developer trying the build for previous release then it will fail as 'sonarRunner task is not available in older version like 1.1, 1,2 & 1,3 etc.
  • So I need to add a generic task (lets say executeGradleTask), which first checks if ‘sonarRunner’ task is available, if yes then it will execute the same, else simple exit.
  • By calling such a generic task, I make sure that the same hudson/jenkins job works, even after adding this gradle task.

You should use a generic lifecycle task in Jenkins, such as "build"
And in your build.gradle file, you should detect if you build the 2.4 version (this depends on your code, so I’ll let you find the best way to achieve this).
For the 2.4 version only, you should apply the sonar runner plug-in, and write "build.dependsOn sonarRunner"
You’re only expressing a task dependency, which is the correct way to do, instead of explicitly executing a task.
I’m not in front of my computer, so I can’t really write a full and clean example. Tell me if you need more than this.

Another element that might help is the “onlyIf” predicate. Read the User Guide for more information about this. You probably could do “sonarRunner.onlyIf()”.

This won’t work in his case since the earlier versions have no such task. Configuring Jenkins to execute it will result in an error. @Francois_Guillot’s solution is the recommended one.

Please note that I am not using ‘execute()’ method for executing the task after checking for its existence, instead after checking for the existance, I am using dependsOn to execute the given task.

I am using something like this in my custom gradle task ‘executeGradleTask()’ :

if (project.tasks.findByPath(['some-gradle-task']) ) {
        dependsOn project.tasks.findByPath(['some-gradle-task'])