2

I have a requirement such that my program is suppose to run for a definite period of time. How could i maintain a timer in java such that the program only runs say for only 30 mins from the program execution start time.

mre
  • 43,520
  • 33
  • 120
  • 170
gautam vegeta
  • 653
  • 6
  • 13
  • 28

3 Answers3

3

You can use java.util.Timer to schedule the time when your program needs to stop. When that time happens, you then need to communicate to your main thread that the program should stop running (unless you simply want to call System.exit).

Taymon
  • 24,950
  • 9
  • 62
  • 84
  • Thanks.This works but i nedd the actual mins passed from the start time as i have to perform other checks alonwith the elapsed time.If other conditions and the time elapsed is greater than the specified mins then I can terminate the program. – gautam vegeta Apr 08 '12 at 13:00
2

Try this (probably in the main method):

Timer t = new Timer();
t.schedule(new TimerTask() {
  @Override
  public void run() {
    System.exit(0);
  }
}, 30*60000);
Richante
  • 4,353
  • 19
  • 23
  • Thanks.This works but i need the actual mins passed from the start time as i have to perform other checks along with the elapsed time.If other conditions and the time elapsed is greater than the specified mins then I can terminate the program. – gautam vegeta Apr 08 '12 at 12:59
  • 2
    You can store the start time of the program by doing: `startTime = System.currentTimeMillis()` at the start of your program. To find out how long the program has been running, do `(System.currentTimeMillis() - startTime) / 60000` – Richante Apr 08 '12 at 13:02
  • If you want to (say) check every minute whether to terminate the program, you can modify the code above - replace `30*60000` with `60000, 60000` (repeat task every minute), and then have an `if` statement in `run()` which checks the condition I provided in the comment, and whatever other checks you want. `startTime` should be a `final long` that is in the same scope as `t`. – Richante Apr 08 '12 at 13:05
2

If you're using a Java version 1.5 or higher, I recommend using the Executors framework. More specifically, a ScheduledExecutorService,

Executors.newSingleThreadScheduledExecutor().schedule(new Runnable(){
    @Override
    public void run(){
        System.exit(0);
    }
}, 30, TimeUnit.MINUTES);

See also Java Timer vs ExecutorService?.

Community
  • 1
  • 1
mre
  • 43,520
  • 33
  • 120
  • 170