Neka
Neka

Reputation: 1664

Run more than one thread using ScheduledExecutorService with same period

I have the ability to work with more than one server in my application. And for each server I need to fetch some info from server into decoupled thread with period in one second.

How to start more than one Runnable with ScheduledExecutorService? Should I use an exclusive executor for each thread, or I can use one executor instance and pass to it all of my runnables that needs to be run each second?

Upvotes: 1

Views: 89

Answers (1)

M A
M A

Reputation: 72884

It seems what you're looking for is ScheduledExecutorService#scheduleAtFixedRate():

Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on.

Here's a simple example:

ScheduledExecutorService executor = Executors.newScheduledThreadPool(NUMBER_OF_THREADS);
executor.scheduleAtFixedRate(new Runnable() {

    @Override
    public void run() {
        // runnable logic           
    }
}, 0, 1, TimeUnit.SECONDS);

You should use one ExecutorService in your application. See the Javadocs for more information about the method.

Upvotes: 1

Related Questions