有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用ScheduledExecutorService方法定期运行一批任务

我想一次提交一批任务,并定期执行它们。使用ExecutorService对象和invokeall方法可以同时运行任务。但是试图使用scheduleAtFixedRate,它不兼容:

executor.scheduleAtFixedRate(executor.invokeAll(callables), initialDelay, period, TimeUnit.SECONDS );

如何一次并定期执行一批任务


共 (1) 个答案

  1. # 1 楼答案

    没有什么像invokeall,但是通过Runnable循环也没有什么错,因为在现实中也没有什么像“立刻”这样的东西:

    ScheduledExecutorService pool = Executors.newScheduledThreadPool(10);
    for (int i = 0; i < 10; i++) {
        pool.scheduleAtFixedRate(() -> {
            // do some work
        }, 0, 10, TimeUnit.SECONDS);
    }
    

    或者,如果您有一个Runnable集合:

    ScheduledExecutorService pool = Executors.newScheduledThreadPool(runnables.size());
    runnables.forEach((r) -> pool.scheduleAtFixedRate(r, 0, 10, TimeUnit.SECONDS));