首页 > 解决方案 > java - 在Java中,如何在执行后自动重新启动可运行列表

问题描述

我有一个List可运行的,由服务返回。这些可运行文件以固定速率安排,延迟一分钟。代码如下所示:

public class Migrator {

// Define one minute in milliseconds.
private static final long INITIAL_DELAY = 60000;
private static final long UPDATE_RATE = 60000;

public static void main(String[] args) {
    final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
    Set<String> dbNames = getDbNames();
    dbNames.forEach(db -> {
        List<Runnable> runnableList = new MigrationTaskManager(db).getRunnableTasksForDB();
        runnableList.forEach(runnable -> {
            executorService.scheduleAtFixedRate(runnable, INITIAL_DELAY, UPDATE_RATE, TimeUnit.MILLISECONDS);
        });
    });
 }
}

执行后,它按预期工作,并且每分钟执行一次可运行文件,如下所示: 在此处输入图像描述

有什么方法可以让runnables它们在完成执行后自动重新启动(无论它们花费多少执行时间),而不是必须使用executorService.scheduleAtFixedRate(runnable, INITIAL_DELAY, UPDATE_RATE, TimeUnit.MILLISECONDS)?我真的可以在这方面使用一些帮助。

标签: javamultithreadingconcurrency

解决方案


public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                                 long initialDelay,
                                                 long delay,
                                                 TimeUnit unit);

这种可以输入延迟的方法,在执行完成+延迟后重新启动runnable。因此,只需延迟 0 即可解决您的问题:

executorService.scheduleWithFixedDelay(runnable, 1, 1, TimeUnit.NANOSECONDS);

推荐阅读