I solved the problem by running nested anonymous execution on every scheduled execution:
final ScheduledExecutorService service = Executors.newScheduledThreadPool(POOL_SIZE); final Runnable command = new SlowRunnable(); service.scheduleAtFixedRate( new Runnable() { @Override public void run() { service.execute(command); } }, 0, 1, TimeUnit.SECONDS);
In this example, there will be 1 thread executing a fast command on each interval, so it will be sure to end when the next interval expires. The remaining POOL_SIZE-1 threads will run SlowRunnable () in parallel, which may take longer than the duration of one interval.
Please note that although I like this solution, since it minimizes the code and reuses the same ScheduledExecutorService, it should be properly configured and may not be used in any context: if SlowRunnable is so slow that before POOL_SIZE the tasks are executed together during There will be no threads running the scheduled task.
Also, if you set the interval to 1 TimeUnit.NANOSECONDS, it will probably become too slow and the execution of the main runnable.
source share