ScheduledExecutorService - Ignore already running

2019-09-16 17:10发布

I'm using a scheduled executor service

private ScheduledExecutorService pool = new ScheduledThreadPoolExecutor(1);

running a runnable at fixed rate

pool.scheduleAtFixedRate(new CoolRunnable(), 10, 10, TimeUnit.MILLISECONDS);

This thread pool waits that the previous execution finishes, but i'd like it to run the runnable every 10 milliseconds no matter whether the previous is done or not.

How can I do that?

EDIT: Fixed the problem replacing the MySQL connection with a connection pool. The normal connection methods are synchronized, that's why the runnables had to wait for each other.

1条回答
Animai°情兽
2楼-- · 2019-09-16 17:57

To do that, you need to submit a task to an ExecutorService every 10s. This ExecutorService is the one that will take care of running the tasks:

ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
ExecutorService workers = Executors.newCachedThreadPool();

scheduler.scheduleAtFixedRate(new Runnable {
    @Override
    public void run() {
        workers.submit(new CoolRunnable());
    }
}, 10, TimeUnit.SECONDS);

Using a cachedThreadPool will create new threads if older ones are still working. Careful in doing so: adding a new task every 10 seconds might create a lot of concurrent threads if the tasks take a lot longer to run.

查看更多
登录 后发表回答