【问题标题】:Java application to start a process and get a callback when events occurred in processJava 应用程序启动进程并在进程中发生事件时获取回调
【发布时间】:2017-01-30 10:09:37
【问题描述】:

我的要求是从 java 启动一个进程并注册该进程的事件回调,例如:启动或终止。

典型场景:

在我的 GUI 应用程序中,我有一个带有“开始/运行”状态文本的“开始进程”按钮。我希望状态在进程运行或未运行时动态变化。 我不想不断检查进程列表并查询我的进程,而是在进程完成时触发回调的一种方式。

【问题讨论】:

  • 如果回调不是实现这一点的任何其他方式的可行方式?

标签: java events callback


【解决方案1】:

快速而简单的解决方案 - Java8 - (以防万一,不知道的人:请参阅 java.lang.Processjava.lang.ProcessBuilder 了解如何开始)

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

public class ProcessObserver
implements Runnable {
  protected Consumer<Process> callback;
  protected Process           toExecute;


  public ProcessObserver(
    Consumer<Process> callback, 
    Process toExecute
  ) {
    super();
    this.callback = callback;
    this.toExecute = toExecute;
  }

  @Override
  public void run() {
    while(this.toExecute.isAlive()) {
      try {
        this.toExecute.waitFor(250, TimeUnit.MILLISECONDS);
      } catch (InterruptedException e) {
        this.toExecute.destroyForcibly();
        return; // Honouring the interrupt request,
                // bail out here and don call the callback
      }
    }
    this.callback.accept(this.toExecute);
  }

  static public void main(String[] args) {
    ThreadPoolExecutor pool=new ThreadPoolExecutor(
        4, 1024, // the threads will mostly sleep in waitFors
        3600, TimeUnit.SECONDS, 
        new LinkedBlockingQueue<Runnable>()
    );

    Process longRunningProcess=null; // initialize it properly
    ProcessObserver observer=new ProcessObserver(
      (Process p)->System.out.println("Exit code of: "+p.exitValue()),
      longRunningProcess
    );
    pool.execute(observer);
  }
}

一个更完善的解决方案将涉及单个线程监视多个进程定期轮询它们并为退出的进程调用相关的回调(毕竟,报告长时间运行的进程的退出代码延迟 0.2s-1s 不会造成差别太大了)。

【讨论】:

    【解决方案2】:

    你可以像下面这样使用 processbuilder

    public class ProcessBuildDemo {
       public static void processdone() {
            System.out.println("processing is done....");
        }
        public static void main(String[] args) throws IOException {  
           String[] command = {"notepad.exe"};
            ProcessBuilder probuilder = new ProcessBuilder( command );
            Process process = probuilder.start();
            // 
            // set status of you button as process is runnning
    
            //Read out dir output
            InputStream is = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            System.out.printf("Output of running %s is:\n",
                    Arrays.toString(command));
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
    
            //Wait to get exit value
            try {
                int exitValue = process.waitFor();
              //set status of you button as process is stop or do call function
                processdone();                  
                System.out.println("\n\nExit Value is " + exitValue);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      您可以尝试类似的方法:

      public interface Callback{
          public void executeCallbackActions();
      }
      
      public static void main(String[] args) {
          Callback callback = new Callback() {
      
              @Override
              public void executeCallbackActions() {
                  System.out.println("Who pressed the button?");
              }
          };
      
          runGui(callback);
      }
      
      public static void runGui(Callback callback){
          //When button is pressed
          callback.executeCallbackActions();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-21
        • 2013-06-07
        • 2021-05-16
        • 2014-10-22
        • 2014-11-02
        • 1970-01-01
        相关资源
        最近更新 更多