如何停止/中断Maven Invoker?

时间:2015-01-20 11:03:48

标签: java maven

我正在做一些软件来帮助我的工作。我正在通过Maven Invoker构建项目:http://maven.apache.org/shared/maven-invoker/usage.html

但是当我打电话给invoker.execute(param);时,我无法以任何方式打断这个。该项目非常庞大,建设时间约为5分钟。如果用户想在2分钟后取消它,他就不能。

执行方法中,我可以看到Runtime.exec(),但我无法访问此过程。

1 个答案:

答案 0 :(得分:0)

回答这个问题可能已经晚了,但我遇到了类似的问题,所以分享我遇到的可能方法,因为它们可能会帮助某人。

1.使用线程中断

从不同的线程中断 invoker.execute(param); 表示工作线程并从可以侦听用户事件的主线程发出中断。例如

Callable<Boolean> c = () -> invoker.execute(param);
FutureTask<Boolean> f1 = new FutureTask<>(c);
Thread t1 = new Thread(f1);
t1.start();

if(user.wantsToCanel()){
  t1.interrupt();//this will send an interrupt to the thread spawning Maven invoker
}

while(!f1.isDone()){
  Thread.sleep(100L);
}

InvocationResult ir = f1.get();

2.强行杀死executor进程

由于`MavenInvoker`在单独的进程中执行maven构建,我们可以通过从不同的线程杀死进程来取消构建。这里的技巧是在 Maven 请求参数中传递一个键来识别要杀死的正确构建。例如
String buildName = "mvn-213";

//Spawning thread with the buildName
List<String> goals = new ArrayList<>();
goals.add("install");
goals.add("-DMvn_Process_name="+ buildName));
InvocationRequest invocationRequest = new DefaultInvocationRequest();
invocationRequest.setGoals(goals);



//From a different thread.
//kill the maven build when user wants to kill that.

String command ="kill $(ps aux | grep '"+buildName+"' | grep -v 'grep' | awk '{print $2}')";
String[] commands = {"bash", "-c", command};
try {
   Runtime.getRuntime().exec(commands);
} catch (Exception t) {
   //do something
}

上述两种方法都需要一个单独的线程来终止/中断 maven 构建。