Question

I am looking for a variant of the ScheduledExecutor that allows for a task to run at a specific interval without waiting for a previous task to complete.

Given the code below, there are 12 different lines of output at intervals of 5000ms.

Given an execution interval of 50ms and a thread pool size of 10, I am looking for a solution that has 10 output lines in the first 550ms, followed by a pause until the threads are freed and can be reused.

    ScheduledExecutorService pollingExecutorService = Executors.newScheduledThreadPool(10);

    final Runnable pollingTask = new Runnable() {
        public void run() {
            System.out.println("running poller " + DateTime.now().toString());
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            System.out.println("5000 passed");
        }
    };

    ScheduledFuture<?> pollingHandler =
            pollingExecutorService.scheduleWithFixedDelay(pollingTask,
                    0,
                    50,
                    TimeUnit.MILLISECONDS);

    //wait secondsIdleBeforeShutdown seconds
    try {
        Thread.sleep(1000*60);
    } catch (InterruptedException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }
Was it helpful?

Solution

try this

    ExecutorService ex = Executors.newFixedThreadPool(10);
    for (;;) {
        List<Future<?>> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Future<?> f = ex.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("running poller " + new Date());
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("5000 passed");
                }
            });
            list.add(f);
        }
        for (Future<?> f : list) {
            f.get();
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top