Yuli Reiri
Yuli Reiri

Reputation: 591

ScheduledExecutorService interrupt periodic execution of concrete tasks

I have a pool of jobs which I run periodically with ScheduledExecutorService help. Now I want to stop periodic execution of some tasks while other tasks should be untouched. What would be the good approach for this meter ?

Upvotes: 4

Views: 136

Answers (1)

Bob Brinks
Bob Brinks

Reputation: 1392

The methods in ScheduledExecutorService return a ScheduledFuture. You could keep a reference to this ScheduledFuture and call cancel on the specific ones you want to cancel.

Maybe save them in a map with an identifier of some sorts so you know which ones to cancel.

ScheduledExecutorService bla;    
//Put a bunch of scheduled stuff in a map
for(int i = 0; i < 10; i++){
    map.put(i, bla.schedule(() -> {}, 10, TimeUnit.DAYS));  
}
//Cancel number 5
map.get(5).cancel(true);

Upvotes: 5

Related Questions