在后台运行JavaExec任务,然后在构建完成时终止 [英] Run JavaExec task in background and then terminate when build completes

查看:165
本文介绍了在后台运行JavaExec任务,然后在构建完成时终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何启动派生Jetty服务器而不阻塞后续任务的JavaExec任务。此外,我将需要在构建完成后终止此服务器。任何想法如何我可以做到这一点?

解决方案

希望这个片段会给你一些关于如何做到这一点的见解。

您可以使用构建侦听器闭包在构建开始/结束时运行代码。然而,出于某种原因, 闭包在里程碑3中不起作用,所以我用替换了它。gradle.taskGraph.whenReady

然后你可以使用<$ c $来调用 runJetty 任务c> Task#execute()(注意,这个API不是官方的,可能会消失),另外,从 ExecutorService 运行它以获取

  import java.util.concurrent。* 

任务myTask<< {
println在这里执行常规任务
}

任务runJetty<< {
print假装我们正在运行Jetty ...
while(!stopJetty){
Thread.sleep(100)
}
printlnJetty停止。
}

stopJetty = false
es = Executors.newSingleThreadExecutor()
jettyFuture = null

//gradle.buildStarted {.. 。}
gradle.taskGraph.whenReady {g - >
jettyFuture = es.submit({runJetty.execute()} as Callable)
}

gradle.buildFinished {
printlnStopping Jetty ...
stopJetty = true

//这是可选的。在调试时可能很有用。
try {
jettyFuture?.get()
} catch(ExecutionException e){
printlnJetty执行过程中出错:
e.printStackTrace()



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?

解决方案

Hope this snippet will give you some insight on how it can be done.

You can used build listener closures to run code on build start/finish. However, for some reason, gradle.buildStarted closure does not work in milestone-3, so I have replaced it with gradle.taskGraph.whenReady which does the trick.

Then you can call the runJetty task using Task#execute() (Note, this API is not official and may disappear), and additionally, run it from an ExecutorService to get some asynchronous behaviour.

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()
  }
}

这篇关于在后台运行JavaExec任务,然后在构建完成时终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆