Aditya Mertia
Aditya Mertia

Reputation: 515

Multiple threads to run parallel at fixed interval using ScheduledExecutorService

Objective: Monitor 5 json URLs every 5 seconds with 5 threads running parallel.

I want to run Multiple parallel threads to monitor JSON URLs at an interval of n-seconds each. I am using ScheduledExecutorService for this.

ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);

for(NetworkBwXmlObject x : xmlDsList) {
    executor.scheduleAtFixedRate(new processJsonUrl(x.getJsonUrl(),x.getId(), ctx), 0, 5, TimeUnit.SECONDS);
}

class processJsonUrl implements Runnable {

}

Is this the right way to create 5 threads to monitor 5 URLS. I don't want to use a thread pool here. All 5 threads have to be active till the lifecycle of the application.

Can ScheduledExecutorService help in my scenario or there is an alternate way to achieve this?

Thanks

Upvotes: 6

Views: 2067

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533880

ScheduledExecutorService is a thread pool and it will do what you want.

Upvotes: 6

the_marcelo_r
the_marcelo_r

Reputation: 1856

I would implement that with Quartz, it's an easy way of achieving good solutions involving scheduled tasks: http://quartz-scheduler.org/

Upvotes: 1

Related Questions