Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / November 2005

Tip: Looking for answers? Try searching our database.

Runtime Exec within Timer Thread

Thread view: 
dagreat - 28 Nov 2005 16:15 GMT
Hello,

I am trying to report system print queue statuses at specified
intervals.  I am using java.util.Timer to implement a repeating task
that does this. My code executes properly when run without using
java.util.Timer.  However, it does not work when using Timer.

--------------------------------------------------
   Runtime.getRuntime().addShutdownHook(new ShutdownHook());

   Timer timer = new Timer(false);
   // get time interval randomly.  The interval will be somewhere
between
   // 9 and 11 minutes.
   GregorianCalendar now = new GregorianCalendar();
   Random randomGen = new Random(now.getTimeInMillis());
   int intervalVariance = randomGen.nextInt(maxIntervalVariance);
   //long interval = minInterval + intervalVariance;
   long interval = 3000;
   // Create The task
   StatusReportTask task = new StatusReportTask(util);
   timer.schedule(task,now.getTime(),interval);

--------------------------------------------------

The code seems to be breaking when making a system call to get a list
of print queues on the system...
String[] cmd = { "/bin/sh", "-c", "lpstat -p | awk '/^printer/ {print
$2}'" };
----------------------------------------------------
   Vector queues = new Vector();
   Runtime rt = Runtime.getRuntime();
   rt.traceInstructions(true);
   String[] cmd = { "/bin/sh", "-c", "lpstat -p | awk '/^printer/
{print $2}'" };
   try {
      Process p = rt.exec(cmd);

      String line;
      // read STDOUT from command
      BufferedReader input = new BufferedReader(new
InputStreamReader(p.getInputStream()));
      while ((line = input.readLine()) != null) {
        if (line != null && line.trim().length() > 0 )
queues.add(line.trim());
      }
      input.close();
      int waitRet = p.waitFor();
      int exitValue = p.exitValue();
System.out.println("exitValue:"+exitValue);

    } catch (Exception e) {
      throw new Exception(e.getMessage()+ ": Could not get print queue
list.");
    }
    String[] strs = new String[queues.size()];
    return (String[])queues.toArray(strs);
 }
--------------------------------------------------

What seems to be happening is that I lose the process after executing
it.  It never seems to return (The exit value does not get printed- as
it should) and an exception is never caught.  It seems that no code is
executed after I call and waitFor the process... except my shutDownHook
is printing some output.  and also... the app should not terminate
because Timer() should keep it running until explicitly killed.
However, it is terminating following the p.exec() call.

Any ideas?

thanks
Roedy Green - 28 Nov 2005 17:28 GMT
> // 9 and 11 minutes.
>    GregorianCalendar now = new GregorianCalendar();
>    Random randomGen = new Random(now.getTimeInMillis());
>    int intervalVariance = randomGen.nextInt(maxIntervalVariance);
>    //long interval = minInterval + intervalVariance;
>    long interval = 3000;

There is no need to fool around with GregorianCalendar.
new Random() seeds itself from the clock by default.

If you need "now" in future, you can get it more easily with
System.currentTimeMillis()
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Roedy Green - 28 Nov 2005 17:31 GMT
>StatusReportTask

The crucial code is in here.  Yet you did not show us that code, or at
least not all of it.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

dagreat - 28 Nov 2005 19:23 GMT
here ya go... thanks for the help.
------------------------------------------------------------------
 public void run() {
   try {
     StatusMap statusMap = new StatusMap();

     Set statuses = statusMap.keySet();
     Iterator statusIt = statuses.iterator();
     while(statusIt.hasNext()) {
       String paramName = (String)statusIt.next();
       // The status reporter knows how to gather the data.
       StatusReporter reporter =
(StatusReporter)statusMap.get(paramName);
       reporter.getStatusFromSystem(appUtil);

       // send report where it needs to go
       reporter.sendReport(url);
     }
   } catch (Exception e)
   {
     // log exception
     appUtil.log(e);
   }
 }
---------------------------------------------------------------
The StatusReporter class is doing the work.  but it fails almost
immediately while doing the system call that I already posted.
Roedy Green - 28 Nov 2005 17:33 GMT
> int waitRet = p.waitFor();

this should read:

ry
        {
        p.waitFor();
        }
     catch ( InterruptedException e )
        {
        Thread.currentThread().interrupt();
        }
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

dagreat - 28 Nov 2005 19:32 GMT
thanks for the help.  I changed the code as you suggested, but I'm
still having the same problem... the application seems to be exiting
without finishing the code, throwing an exception or anything.  I even
added some code to catch the more general Throwable, but I still get
nothing.
---------------------------------------------
code here.....

      p.waitFor();
      exitValue = p.exitValue();
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      System.out.println("Interupted thread");
    } catch (Exception e) {
      System.out.println("Exeption");
      exception = e;
    } catch (Throwable t) {
       System.out.println("Throwable");
    }
--------------------------------------------------------

I should also add that reading STDOUT from the process also causes the
same behavior... although reading STDERR doesn't seem to.
dagreat - 28 Nov 2005 20:10 GMT
Just an update...  I added...

while (true) {}

...after scheduling the timer task, and it no longer dies.  I thought
that it was supposed to keep running without brute force, though. Could
this problem be specific to the Linux RTE?


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.