Solved

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

Posted on 2009-05-09
12
923 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
  • 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 500 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
 
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

705 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now