Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run JavaExec task in background and then terminate when build completes

Tags:

gradle

jetty

I'm trying to figure out how to launch a JavaExec task that spawns a Jetty server without blocking subsequent tasks. Also, I will need to terminate this server after the build completes. Any idea how I can do this?

like image 911
Ray Nicholus Avatar asked Oct 23 '11 03:10

Ray Nicholus


2 Answers

I know the thread is from 2011, but I still stumbled across the problem. So here's a solution working with Gradle 2.14:

import java.util.concurrent.Callable
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors    

class RunAsyncTask extends DefaultTask {
    String taskToExecute = '<YourTask>'
    @TaskAction
    def startAsync() {
        ExecutorService es = Executors.newSingleThreadExecutor()
        es.submit({taskToExecute.execute()} as Callable)
    }
}


task runRegistry(type: RunAsyncTask, dependsOn: build){
    taskToExecute = '<NameOfYourTaskHere>'
}
like image 171
chrishuen Avatar answered Nov 16 '22 03:11

chrishuen


I updated solution from @chrishuen because you cannot call execute on task anymore. Here is my working build.gradle

import java.time.LocalDateTime
import java.util.concurrent.Callable
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

group 'sk.bsmk'
version '1.0-SNAPSHOT'

apply plugin: 'java'

task wrapper(type: Wrapper) {
  gradleVersion = '3.4'
}

class RunAsyncTask extends DefaultTask {
  @TaskAction
  def startAsync() {
    ExecutorService es = Executors.newSingleThreadExecutor()
    es.submit({
      project.javaexec {
        classpath = project.sourceSets.main.runtimeClasspath
        main = "Main"
      }
    } as Callable)

  }
}

task helloAsync(type: RunAsyncTask, dependsOn: compileJava) {
  doLast {
    println LocalDateTime.now().toString() + 'sleeping'
    sleep(2 * 1000)
  }
}
like image 38
bsmk Avatar answered Nov 16 '22 04:11

bsmk