Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run java function for only 30 minutes

I need to create a java function that will only run for 30 minutes, and at the end of the 30 minutes it executes something. But it should also be able to self terminate before the given time if the right conditions are met. I don't want the function to be sleeping as it should be collecting data, so no sleeping threads.

Thanks

like image 512
Angel Grablev Avatar asked Sep 29 '10 21:09

Angel Grablev


1 Answers

Use: Timer.schedule( TimerTask, long )

public void someFunctino() {
    // set the timeout    
    // this will stop this function in 30 minutes
    long in30Minutes = 30 * 60 * 1000;
    Timer timer = new Timer();
    timer.schedule( new TimerTask(){
          public void run() {
               if( conditionsAreMet() ) { 
                   System.exit(0);
                }
           }
     },  in30Minutes );

     // do the work... 
      .... work for n time, it would be stoped in 30 minutes at most
      ... code code code
}
like image 60
OscarRyz Avatar answered Oct 05 '22 07:10

OscarRyz