Run the JavaExec task in the background, and then exit when the build is complete

I am trying to figure out how to run a JavaExec task that spawns a Jetty server without blocking subsequent tasks. In addition, I will need to complete this server after the build is complete. Any idea how I can do this?

+6
source share
4 answers

We hope this snippet gives you some insight into how this can be done.

You can use the locks of the collector to run the code at the start / end of the assembly. However, for some reason, closing gradle.buildStarted does not work in milestone 3, so I replaced it with gradle.taskGraph.whenReady , which does the trick.

You can then call the runJetty task with Task#execute() (note that this API is not official and may disappear), and also run it from ExecutorService to get some asynchronous behavior.

 import java.util.concurrent.* task myTask << { println "Do usual tasks here" } task runJetty << { print "Pretend we are running Jetty ..." while(!stopJetty){ Thread.sleep(100) } println "Jetty Stopped." } stopJetty = false es = Executors.newSingleThreadExecutor() jettyFuture = null //gradle.buildStarted { ... } gradle.taskGraph.whenReady { g -> jettyFuture = es.submit({ runJetty.execute() } as Callable) } gradle.buildFinished { println "Stopping Jetty ... " stopJetty = true //This is optional. Could be useful when debugging. try{ jettyFuture?.get() }catch(ExecutionException e){ println "Error during Jetty execution: " e.printStackTrace() } } 
+1
source

I know the thread has been since 2011, but I still stumbled over a problem. So, the 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>' } 
+4
source

I updated the solution from @chrishuen because you can no longer call execute on task. Here is my build.gradle work

 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) } } 
+3
source

You cannot do this with JavaExec ; You will have to write your own task.

+1
source

Source: https://habr.com/ru/post/899891/


All Articles