简体   繁体   中英

ScheduledExecutorService - Ignore already running runnable

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM