简体   繁体   中英

Running a method/function for a specified time

I'm looking for a easy way to execute a method/function for specified time in java. Something that would be like this:

for(3 secs){
   x();
}

The way should be easy to implement AND should have a good performance aswell.

long startTime = System.currentTimeMillis();
while(System.currentTimeMillis() - startTime <= 3000){
  x();
}

+1 for Aaron's answer, with using long finishTime = System.currentTimeMillis() + 3000 instead, moving the addition / subtraction outside of the loop, leaving only the comparison for efficiency / performance.

Note however, that once you enter x(), and if x() takes a while to run, the overall loop may run for longer than your desired time. If x() is length, you may want to add checks for the stop condition within it as well.

I'd do

long finishTime = System.currentTimeMillis()+3000;
while(System.currentTimeMillis() <= finishTime){
  x();
}

to move the arithmetic outside the loop, for efficiency/performance

void run ( Runnable task , long milliseconds ) throws Exception
{
       new Thread ( )
       {
              public void run ( ) 
              {
                     while ( true )
                     {
                              task . run ( ) ;
                     }
              }
       } . start ( ) ;
       Thread . sleep ( milliseconds ) ;
       System . exit ( 0 ) ;
}

This will work even if the task takes longer than the time alloted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM