Home > Enterprise >  How to I check whether a process is started or not in Java
How to I check whether a process is started or not in Java

Time:10-10

I have a question related to Process creation in java. The main scenario is that I want to show a progress bar/spin loader until the process gets started Below is the code for starting a process using java.

ProcessBuilder processBuilder = new ProcessBuilder("python", filename);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();

How exactly I will know that this process is started. Thanks

CodePudding user response:

The ProcessBuilder#start() method starts the process as soon as you call the method. If the executable file is not found it throws IOException. If everything is ok, your process is surely started. Yes, the process may take some time to get loaded but it is the time taken by the process to response. It gets started immediately.

Try running notepad by this code

System.out.println("Starting...");
new ProcessBuilder("notepad").start();

As soon as Starting... is printed you will see the Notepad window popping up. Again it depends on your processor speed. A lightweight application like Notepad may pop out immediately, but a heavyweight application like Android Studio may take some time to pop out. But whatever the process maybe it starts immediately.

CodePudding user response:

Okay so I made a solution for my problem. I used the thread class with process to perform my required task Here's what I have done

Loader loader = new Loader();
        loader.setVisible(true);
        Thread t1 = new Thread(new Runnable(){
            @Override
            public void run() {
                Timer timer = new Timer(1000, new ActionListener() {
                private int count = 4;
                @Override
                public void actionPerformed(ActionEvent e) {
                        if (count <= 0) {
                            loader.setVisible(false);
                            ((Timer)e.getSource()).stop();
                        } else {
                            count--;
                        }
                    }
                });
                timer.start();
            }
        });
        t1.start();

Where Loader is my simple class having a gif in panel to show for 4 seconds

  • Related