繁体   English   中英

如何重复运行多个任务并在Java中经过一定时间后将其停止

[英]How to run a number of task repeatedly and stop it after a certain amount of time in java

我已经看到了答案的一部分,但还没有完整。

我知道,如果您想同时运行多个任务,则想将ThreadRunnable实现一起使用

我已经看到,如果您想运行像这样的重复性任务,可以使用ScheduledExecutorService

Runnable helloRunnable = () -> System.out.println("Hello world " + LocalDateTime.now().toLocalTime().toString());
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(helloRunnable, 0, 10, TimeUnit.SECONDS);

但这仅运行一个线程,并且在一定时间后没有杀死进程的方法或参数

我想做的是每10秒并行运行5次相同的任务,持续10分钟


编辑

如果将来的人们对它的完整示例感兴趣,请参见:

public static void main(String[] args) {
    Runnable helloRunnable = () -> System.out.println("Hello world " + LocalDateTime.now().toLocalTime().toString());
    Runnable testRunnable = () -> System.out.println("Test runnable " + LocalDateTime.now().toLocalTime().toString());

    List<Runnable> taskList = new ArrayList<>();
    taskList.add(helloRunnable);
    taskList.add(testRunnable);

    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    List <ScheduledFuture<?>> promiseList = new ArrayList<>();
    for (Runnable runnable : taskList) {
        ScheduledFuture<?> promise = executor.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);
        promiseList.add(promise);
    }

    List <Runnable> cancelList = new ArrayList<>();
    for (ScheduledFuture<?> promise : promiseList) {
        Runnable cancelRunnable = () -> {
            promise.cancel(false);
            executor.shutdown();
        };
        cancelList.add(cancelRunnable);
    }

    List <ScheduledFuture<?>> canceledList = new ArrayList<>();
    for (Runnable runnable : cancelList){
        ScheduledFuture<?> canceled = executor.schedule(runnable, 10, TimeUnit.SECONDS);
        canceledList.add(canceled);
    }
}

TL; DR:计划另一个任务以取消第一个任务。

首先, 不要忽略返回值 -这是一种进入,停止这样做并练习不这样做的坏习惯。 ScheduledExecutorService.scheduleAtFixedRate方法返回ScheduledFuture<?> -这使您可以取消任务!

因此,要每10秒运行一次任务1分钟:

final Runnable helloRunnable = () -> System.out.println("Hello world " + LocalDateTime.now().toLocalTime().toString());
final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
final ScheduledFuture<?> promise = executor.scheduleAtFixedRate(helloRunnable, 0, 10, TimeUnit.SECONDS);
final ScheduledFuture<Boolean> canceller = executor.schedule(() -> promise.cancel(false), 1, TimeUnit.MINUTES);

另外要注意的是,如果你从来没有打电话getFuture ,你永远不知道,如果任务失败-这意味着你需要另一个 Thread来等待promise.get所以,如果一个Exception被抛出,你马上就知道出了问题。

然后,问题是谁在监视监视线程 因此,如果您需要强大的功能,您会很快发现自己重新实现了任务计划库。


还要注意有用的实用程序方法Executors.newSingleThreadScheduledExecutor()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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