Intervene in ScheduledThreadPoolExecutor Schedule

I used ScheduledThreadPoolExecutor.scheduledAtFixedRate to schedule some task to start each dt interval.

But sometimes I want to get a task to execute immediately. After completing the task, I want the graph to return to normal. (i.e. for some time dt after this "forced" execution, the task must be completed again).

Is it possible to do this with ScheduledThreadPoolExecutor ? Could you show me how? Some simple example would be great!

I assume this can be done by simply disabling the schedule, completing the task manually, and calling scheduleAtFixedRate again, but I wonder how good practice is.

thanks

+4
source share
2 answers

That's a good question. Perhaps you could call cancel() on the ScheduledFuture<T> that you received from the scheduledAtFixedRate() call, send the task manually using submit() , and then reassign the fixed rate task when Future returns? You would have to check that the task is not running yet, I suppose.

Some pseudo codes ...

 ScheduledFuture<Thingy> sf = executor.scheduleAtFixedRate(myTask, etc...); sf.cancel(); final Future<Thingy> f = executor.submit(myTask); f.get(); sf = executor.scheduleAtFixedRate(myTask, etc...); 

I have never done this, this is an interesting question.

+2
source

To execute a single frame, use

 ScheduledFuture<Thingy> sf = executor.schedule(myTask, 0, SECONDS); 

This will execute myTask once and immediately, but will not stop the scheduled tasks at intervals. Is this really a problem?

-1
source

All Articles