A. Vreeswijk
A. Vreeswijk

Reputation: 954

Java ScheduledFuture doesn't wait for task to finish

I have problem. I am using the following code:

ScheduledExecutorService tradingPool = Executors.newScheduledThreadPool(1);
Runnable runTradingTask = () -> {
    new TradingDriver().run();
};
ScheduledFuture<?> scheduledTradingFuture = tradingPool.scheduleAtFixedRate(runTradingTask, 0, 1, TimeUnit.SECONDS);

In my TradingDriver.run() I have a few SQL statements, so that takes some time, arround 1.5 seconds, but I noticed that the next run already started. To check if my thoughts were right I printed "Started" and "Ended" at the endpoints of the function. And this was my result:

Started
Started
Ended
Started
Ended
Started
Ended
Started

As you can see it prints 2x "Started", so that means another run gets started while the first one didn't finish. Now I have seen this post: ScheduledExecutorService wait for task to complete, but I can see that the ScheduledFuture doesn't wait for finish.

How can I run the TradingDriver.run() continuously with 1 second between executions?

Upvotes: 0

Views: 350

Answers (1)

tremendous7
tremendous7

Reputation: 751

use scheduleWithFixedDelay instead of scheduleAtFixedRate

Upvotes: 1

Related Questions