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
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).
1 Comment
gautam vegeta
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.
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
gautam vegeta
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.
Richante
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) / 60000Richante
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.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?.