简体   繁体   中英

interfere with ScheduledThreadPoolExecutor's schedule

I used ScheduledThreadPoolExecutor.scheduledAtFixedRate to schedule some task to run every dt interval.

But sometimes, I do want to force the task to be executed immediately. After the task has executed, I want the schedule to go back to normal. (ie., some dt amount of time after this 'forced' execution, the task should be executed again).

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

I suppose one could do this by simply shutting down the schedule, executing the task manually, and calling scheduleAtFixedRate again, but I'm wondering if that's good practice.

Thanks

That's a good question. Maybe you could call cancel() on the ScheduledFuture<T> that you received from calling scheduledAtFixedRate() , submit the task manually using submit() , and then reschedule your fixed rate task again when that Future comes back? You would have to check that the task isn't already running I suppose.

Some pseudocode...

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

I've never done it, it's an interesting question.

For a one shot execution use

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

This will execute myTask once and immediate but won't stop executing the tasks scheduled before with an interval. Is that really a problem?

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