Alasdair
Alasdair

Reputation: 14113

How To Limit Max Execution Time for Java App from Command Line

How do I limit the maximum execution time when executing a java app from command line, like this:

java -Xmx10G -cp /weka/weka.jar weka.classifiers.trees.J48 -t /test/test-vector.arff -d /test/test.model

Upvotes: 1

Views: 1013

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500675

I don't believe there's anything built into Java to do this for you. Options:

  • Write a wrapper class which launches the original class but also creates a timer thread to kill the current process if it hasn't finished in time.
  • Use the operating system capabilities

As an example of the latter, in bash on Unix-like systems you could use ulimit -t [seconds] before starting the process.

EDIT: As noted in comments, it's not clear how graceful such a shutdown with ulimit would be - whether the threads would be killed in a sufficiently polite way to allow finally blocks to execute etc. That's probably something worth testing out.

EDIT: Again as per comments, ulimit limits the CPU time, not the overall wall time. This may or may not be what you're after - it depends if your process is CPU-bound.

Upvotes: 4

Shivan Dragon
Shivan Dragon

Reputation: 15219

Well, you can user Java's scheduler to have it shut down the application after a certain time:

http://download.oracle.com/javase/1,5.0/docs/api/java/util/Timer.html

Upvotes: 2

Related Questions