Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2009-05-09
12
Medium Priority
?
934 Views
Last Modified: 2012-05-06
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

0
Comment
Question by:tia_kamakshi
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 6
12 Comments
 
LVL 92

Expert Comment

by:objects
ID: 24346199
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
 
LVL 92

Accepted Solution

by:
objects earned 2000 total points
ID: 24346210
 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
 

Author Comment

by:tia_kamakshi
ID: 24347632
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 92

Expert Comment

by:objects
ID: 24347803
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
 

Author Comment

by:tia_kamakshi
ID: 24350415
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
 
LVL 92

Expert Comment

by:objects
ID: 24350430
the code I posted earlier will handle that

0
 

Author Comment

by:tia_kamakshi
ID: 24440199

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
 
LVL 92

Expert Comment

by:objects
ID: 24440212
error suggests you have changed one class with recompiling others. Try rebuilding all your classes.

0
 

Author Comment

by:tia_kamakshi
ID: 24440247
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
 
LVL 92

Expert Comment

by:objects
ID: 24440315
because your ProcessRequests class is failing to call it
recompile ProcessRequests.java

0
 

Author Comment

by:tia_kamakshi
ID: 24440606
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
 

Author Closing Comment

by:tia_kamakshi
ID: 31579837
Many Thanks
0

Featured Post

Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Suggested Courses

722 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question