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.

3 Answers 3

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).

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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);

3 Comments

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.
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
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.
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?.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.