Search code examples
linuxapijobsjava

Linux shell jobs api for Java


Are there any APIs available in Java to query jobs? In other words, I am looking for api for "jobs" command so that I can get to know status of jobs (running, stopped etc). Ideally, I would like to be able to submit jobs but I think it can be achieved easily by calling shell and pass &


Solution

  • If you have/develop - shell script to handle Job , then you can use java.lang.process apis to execute that shell script and see if it can serve your purpose. You can also pass arguments along with parameters. Following is the code snippets may be useful to you.

    import java.io.IOException;
    import java.io.InputStream;
    
    
    public class MYProcess
    {
       int startProcess()
       {
          String cmd = "/opt/test/bin/mystart.sh"
    
          // create a process for the shell
          ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
       // use this to capture messages sent to stderr
          pb.redirectErrorStream(true);                                      
          Process shell = null;
          int shellExitStatus =-1;     
          try
          {
             shell = pb.start();
          }
          catch (IOException e)
          {
             e.printStackTrace();
          }
          InputStream shellIn = shell.getInputStream();
          try
          {
             shellExitStatus = shell.waitFor();
             //logger.info("call exit status:" + shellExitStatus);
             //logger.info("If exit status is not zero then call is not successful. Check log file.");        
          }
          catch (InterruptedException e)
          {
             //logger.error("error while call" + e);
             e.printStackTrace();
          } // wait for the shell to finish and get the return code
          return shellExitStatus;
       }
    }