Reputation: 23547
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
Upvotes: 4
Views: 251
Reputation: 20614
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?
Upvotes: -1
Reputation: 31720
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.
Upvotes: 2