当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Force method run during specified interval of time

问题描述:

I want to force method run for specified time.

 public Response run(Request req){

//method runImpl must run during specified interval of time(for example for 10 secs)

Response res = runImpl(req);

return response;

}

What is the best way to do this?Thanks!

网友答案:

runImpl should return a boolean for this code to work. You'll probably want this in a new Thread (basic tutorials abound) if you don't want your program stalled until it finishes.

public Response run(Request req){
long lasttime=Sys.getTime();
int i=0;
while(i<10){
   if(Response res = runImpl(req);){
   return response;
   }
   if((Sys.getTime-lasttime)>1000){
   i++;
   lasttime=Sys.getTime();
   }
}
return null;

This runs every processor moment, if you want it to run on an interval AS WELL as running for 10 seconds, use:

public Response run(Request req){
long lasttime=Sys.getTime();
int i=0;
for(int i; i<(10000/yourchoiceinterval); i++){
   if(Response res = runImpl(req);){
   return response;
   }
   if((Sys.getTime-lasttime)>1000){
   lasttime=Sys.getTime();
   }
}
return null;
网友答案:

Try to use this:

poolExecutor = new ScheduledThreadPoolExecutor(1);
poolExecutor.scheduleAtFixedRate(
        new YourRunable(), startFrom/*10*/, startEvery/*5*/, TimeUnit.SECONDS);
网友答案:

Best method would be to make your work in chunks of appropriate size, so each chunk can be done in, say, 1 second. This way at the end of each chunk you can check if time is elapsed.

If your work involves I/O work which can block for indefinite time, try to use interruptible methods (which can be interrupted by call to Thread.interrupt()) or methods which accept explicit max running time from caller.
Or you can delegate I/O work to some dedicated thread and check it's progress in separate thread, and act appropriately when running time is exceeded.

网友答案:

You could start a new thread that only calls your method and put it to sleep after a timer you create expires. That way though you can't guarantee that the method cycle has completed before suspending, but does the trick without having to modify the method. For you to achieve cycles, just put this logic of sleeping inside the thread's loop. Just remember to wake up the thread

There may be dozens of implementations since you didn't explained clear enough.

分享给朋友:
您可能感兴趣的文章:
随机阅读: