Michael T
Michael T

Reputation: 339

ScheduledExecutorService, schedule different tasks at different intervals

I want to have two tasks - HandlerA and HandlerB being executed every 10 and every 20 seconds respectively. If this solution is wrong, what is the best way to achieve this?

ScheduledExecutorService stp = Executors.newScheduledThreadPool(8);
stp.scheduleAtFixedRate(new HandlerA(), 0, 10, TimeUnit.SECONDS);
stp.scheduleAtFixedRate(new HandlerB(), 0, 20, TimeUnit.SECONDS);

is the scheduled task overwritten, when I schedule another one?

Upvotes: 2

Views: 2518

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136152

Your solution is correct. You are scheduling 2 separate tasks. Your ScheduledThreadPoolExecutor has core pool size = 8, this is more than enough to execute 2 scheduled tasks in parallel.

Upvotes: 3

Marcel Stör
Marcel Stör

Reputation: 23565

Why do you ask? That solution is fine. Each invocation of scheduleAtFixedRate starts an individual scheduler i.e. adding HandlerA twice runs it with two independent schedulers.

Upvotes: 1

Related Questions