The force method starts within a specified time interval.

I want to force a method to run a specific 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? Thank!

+5
source share
4 answers

runImpl must return a boolean for this code to work. You probably want this to be in a new topic (basic tutorials abound) if you don't want your program to stall until it ends.

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 starts every processor moment, if you want it to work with an AS WELL interval 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;
+2
source

Try using this:

poolExecutor = new ScheduledThreadPoolExecutor(1);
poolExecutor.scheduleAtFixedRate(
        new YourRunable(), startFrom/*10*/, startEvery/*5*/, TimeUnit.SECONDS);
+3
source

, , , 1 . , , .

-, , ( Thread.interrupt()) , . - , .

+1

You can start a new thread that calls your method only after the timer you set expires. Thus, although you cannot guarantee that the method loop was completed before the suspension, it does the trick without having to modify the method. So that you can achieve the loops, just put this sleep logic inside the thread loop. Just remember to spill the thread

There may be dozens of implementations, as you have not explained clearly enough.

0
source

All Articles