Running .bat file in some different thread or wait .bat file response till some given time

Hi,

I am running .bat file from my java code

This .bat file runs some another java application program

It works great, if .bat file executed successfully

But in case if some error comes or other program terminates for some reason then my loops wait forever for the response of .bat file

I wanted whether my .bat file runs in some differnt thread and that threads exits after some time

or

My application waits for some time to respond , If .bat file does not respond.

My main program loop should run and my program should not hang because other program is not responding well

I am executing below method to run .bat file, which is called inside some loop and this .bat file is executed on at some conditions

Please guide
public static void runbatch(String strNewsletterID, NewsletterOutlookConfBO newsletterOutlookConf, NewsletterBO newsletterBO)
            throws Exception
    {        
        System.out.print("Running .bat file from location "+newsletterOutlookConf.BatchFilePath);
                      Process p = Runtime.getRuntime().exec("cmd /C "+newsletterOutlookConf.BatchFilePath+ " "+ newsletterBO.NewsletterAction+ " "+strNewsletterID);
 
/**************************** NO NEEDS FOLLOWING IF RUN C:\EYEDRIOPPER.EXE ***************/
                     BufferedReader in = new BufferedReader(
                                         new InputStreamReader(p.getInputStream()));
                     String line = null;
                     while ((line = in.readLine()) != null) {
                         System.out.println(line);
                     }
 
/*****************************************************************************************/
 
    }

Open in new window

tia_kamakshiAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

objectsCommented:
you should be reading stderr as well as stdout

to kill it after a certain time you can use a Timer, or run it in a separate thread and use Thread..join() method to wait a certain amount of time before killing it

0
objectsCommented:
 Runtime runtime = Runtime.getRuntime();
  Process process = runtime.exec(commandLine);
  /* Set up process I/O. */
  ...
  Worker worker = new Worker(process);
  worker.start();
  try {
    worker.join(timeout);
    if (worker.exit != null)
      return worker.exit;
    else
      throw new TimeoutException();
  } catch(InterruptedException ex) {
    worker.interrupt();
    Thread.currentThread().interrupt();
    throw ex;
  } finally {
    process.destroy();
  }
}

private static class Worker extends Thread {
  private final Process process;
  private Integer exit;
  private Worker(Process process) {
    this.process = process;
  }
  public void run() {
    try {
      exit = process.waitFor();
    } catch (InterruptedException ignore) {
      return;
    }
  }  
}

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
tia_kamakshiAuthor Commented:
Many thanks for your help

Where in above code I should call my method

FindNewMail.runbatch((strNewsletterID, newsletterOutlookConf, newsletterBO);

and wait to for max  30 min process to execute in different thread.

Thanks again for your response.
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

objectsCommented:
you would add above to runBatch()

public static void runbatch(String strNewsletterID, NewsletterOutlookConfBO newsletterOutlookConf, NewsletterBO newsletterBO)
            throws Exception

 Runtime runtime = Runtime.getRuntime();
  Process process = runtime.exec(commandLine);
  /* Set up process I/O. */
  ...
  Worker worker = new Worker(process);
  worker.start();
  .....


If you want it done in a separate thread then the easiest would be to call runBatch() form a new thread
(a utility method could be used for that)


new Thread(new Runnable() {
   public void run() {
       runBatch(.....
   }
});



0
tia_kamakshiAuthor Commented:
Many Thanks,

If I use
new Thread(new Runnable() {
   public void run() {
       runBatch(.....
   }
});

Then how can I destroy thread after max 30 min. if thread not broken

because my batch file will run in infinite loop and running batch depends on the request comes from external source.

So, if my process nit completed then I wanted my thread to live max after 30 min.

If my process completes then my thread should be destroyed instantly rather than waiting for 30 min

Many Thanks
0
objectsCommented:
the code I posted earlier will handle that

0
tia_kamakshiAuthor Commented:

Hi,

Sorry for the late response, Now I am trying code as you have suggested.

I get error

Exception in thread "main" java.lang.NoSuchMethodError: smecoutlook.FindNewMail.runbatch(Ljava/lang/String;Lcom/pbms/smecoutlook/businessobjects/NewsletterOutlookConfBO;Lcom/pbms/smecoutlook/businessobjects/NewsletterMailsBO;)V
        at com.pbms.smecoutlook.businesslogic.ProcessRequests.createNewSubsequentCampaign(ProcessRequests.java:758)
        at com.pbms.smecoutlook.businesslogic.ProcessRequests.processSetUpRequest(ProcessRequests.java:113)
        at smecoutlook.FindNewMail.handleNewMail(FindNewMail.java:246)
        at smecoutlook.FindNewMail.findnewMails(FindNewMail.java:105)
        at smecoutlook.SMECOutlookMain.main(SMECOutlookMain.java:69)
Java Result: 1
BUILD SUCCESSFUL (total time: 42 seconds)


AND MY MAIN LOOP ALSO EXISTS


public Integer runbatch(String strNewsletterID, NewsletterOutlookConfBO newsletterOutlookConf, NewsletterMailsBO newsletterMailsBO)
            throws Exception
    {

        final String strnewsletterIDF =  strNewsletterID;
        final NewsletterOutlookConfBO newsletterOutlookConfF =  newsletterOutlookConf;
        final NewsletterMailsBO newsletterMailsBOF =  newsletterMailsBO;

        Process p  = Runtime.getRuntime().exec("cmd /C "+newsletterOutlookConf.BatchFilePath+ " "+
                                            newsletterMailsBO.newsletterBO.NewsletterAction+ " "+strNewsletterID+" "+ newsletterMailsBO.FromAddress+" "+ newsletterMailsBO.newsletterBO.NewsletterRefno);


        BufferedReader in = new BufferedReader(
                                         new InputStreamReader(p.getInputStream()));
                     String line = null;
                     while ((line = in.readLine()) != null) {
                         System.out.println(line);
                     }


    Worker worker = new Worker(p);
    worker.start();

    try {
    worker.join(100000000);

    if (worker.exit != null)
      return worker.exit;
    else
      throw new TimeoutException();
  } catch(InterruptedException ex) {
    worker.interrupt();
    Thread.currentThread().interrupt();
    throw ex;
  } finally {
    p.destroy();
  }
       
    }
   
   
   


AND WHEN I am running below code

My code is not going even in main thread


public void runbatch(String strNewsletterID, NewsletterOutlookConfBO newsletterOutlookConf, NewsletterMailsBO newsletterMailsBO)
            throws Exception
    {

        final String strnewsletterIDF =  strNewsletterID;
        final NewsletterOutlookConfBO newsletterOutlookConfF =  newsletterOutlookConf;
        final NewsletterMailsBO newsletterMailsBOF =  newsletterMailsBO;

        Thread thread = new Thread(new Runnable() {

            public void run() {
                try
                {
                    runBatchProcessInThread(strnewsletterIDF, newsletterOutlookConfF, newsletterMailsBOF);
                }catch(Exception ex)
                {
                    mL.error("Error in running batch process", ex);
                }
            }
        });



        /*
//                     Process p = Runtime.getRuntime().exec("c:\\EyeDropper.exe");
                        System.out.print("Running .bat file from location "+newsletterOutlookConf.BatchFilePath);
                       
                      Process p = Runtime.getRuntime().exec("cmd /C "+newsletterOutlookConf.BatchFilePath+ " "+
                                            newsletterMailsBO.newsletterBO.NewsletterAction+ " "+strNewsletterID+" "+ newsletterMailsBO.FromAddress+" "+ newsletterMailsBO.newsletterBO.NewsletterRefno);

/ **************************** NO NEEDS FOLLOWING IF RUN C:\EYEDRIOPPER.EXE *************** /
                     BufferedReader in = new BufferedReader(
                                         new InputStreamReader(p.getInputStream()));
                     String line = null;
                     while ((line = in.readLine()) != null) {
                         System.out.println(line);
                     }

/***************************************************************************************** /
 
 */

    }
   
   
Please guide

Many Thanks for your co-operation
0
objectsCommented:
error suggests you have changed one class with recompiling others. Try rebuilding all your classes.

0
tia_kamakshiAuthor Commented:
Thanks, But which one is the correct code

As if I see my attached code

I am executing batch file first and then latter on I am starting worker process.

But in this case if my .bat processhangs for some reason then it will never come to worker process line

Please guide

Many Thanks
public Integer runbatch(String strNewsletterID, NewsletterOutlookConfBO newsletterOutlookConf, NewsletterMailsBO newsletterMailsBO)
            throws Exception
    {
 
        final String strnewsletterIDF =  strNewsletterID;
        final NewsletterOutlookConfBO newsletterOutlookConfF =  newsletterOutlookConf;
        final NewsletterMailsBO newsletterMailsBOF =  newsletterMailsBO;
 
        Process p  = Runtime.getRuntime().exec("cmd /C "+newsletterOutlookConf.BatchFilePath+ " "+
                                            newsletterMailsBO.newsletterBO.NewsletterAction+ " "+strNewsletterID+" "+ newsletterMailsBO.FromAddress+" "+ newsletterMailsBO.newsletterBO.NewsletterRefno);
 
 
        BufferedReader in = new BufferedReader(
                                         new InputStreamReader(p.getInputStream()));
                     String line = null;
                     while ((line = in.readLine()) != null) {
                         System.out.println(line);
                     }
 
 
    Worker worker = new Worker(p);
    worker.start();
 
    try {
    worker.join(100000000);
 
    if (worker.exit != null)
      return worker.exit;
    else
      throw new TimeoutException();
  } catch(InterruptedException ex) {
    worker.interrupt();
    Thread.currentThread().interrupt();
    throw ex;
  } finally {
    p.destroy();
  }
        
    }

Open in new window

0
objectsCommented:
because your ProcessRequests class is failing to call it
recompile ProcessRequests.java

0
tia_kamakshiAuthor Commented:
Thanks,

I am using below code as you have suggested.

For test I am trying to wait for my process to wait for max 100 milli seconds and if it does not respond then exit the process and my main loop continue.

And I wanted this in always in new thread

But my code is not working well. It is waiting for long if my process do not respond for long

For test purpose I have slept my application calling from batch file for

Thread.sleep(1000000000);

And it is waiting for long to respond which I donot wanted

Please guide

Many Thanks
public Integer runbatch(String strNewsletterID, NewsletterOutlookConfBO newsletterOutlookConf, NewsletterMailsBO newsletterMailsBO)
            throws Exception
    {
 
        final String strnewsletterIDF =  strNewsletterID;
        final NewsletterOutlookConfBO newsletterOutlookConfF =  newsletterOutlookConf;
        final NewsletterMailsBO newsletterMailsBOF =  newsletterMailsBO;
 
        Process p  = Runtime.getRuntime().exec("cmd /C "+newsletterOutlookConf.BatchFilePath+ " "+
                                            newsletterMailsBO.newsletterBO.NewsletterAction+ " "+strNewsletterID+" "+ newsletterMailsBO.FromAddress+" "+ newsletterMailsBO.newsletterBO.NewsletterRefno);
 
 
        BufferedReader in = new BufferedReader(
                                         new InputStreamReader(p.getInputStream()));
                     String line = null;
                     while ((line = in.readLine()) != null) {
                         System.out.println(line);
                     }
 
 
    Worker worker = new Worker(p);
    worker.start();
 
    try {
    worker.join(100);
 
    if (worker.exit != null)
      return worker.exit;
    else
      throw new TimeoutException();
  } catch(InterruptedException ex) {
    worker.interrupt();
    Thread.currentThread().interrupt();
    throw ex;
  } finally {
    p.destroy();
  }
        
    }

Open in new window

0
tia_kamakshiAuthor Commented:
Many Thanks
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.