简体   繁体   中英

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

I've seen a here and there part's of my answer but not a complete one.

I know that if you want tu run multiple task at the same time you want to use Thread with Runnable implementation

I've seen that you can use the ScheduledExecutorService if you want to run repetitive tasks like this :

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

But this run just one thread and does not have method or parameter to kill the process after a certain time

What I would like to do is to run 5time the same task in parallel every 10seconds for 10minutes


Edit

If future people are interested in full example of it here it is :

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: Schedule another task to cancel the first.

First things first, don't ignore return values - this is bad habit to get into, stop doing it and practice not doing it. The method ScheduledExecutorService.scheduleAtFixedRate returns a ScheduledFuture<?> - this allows you to cancel the task!

So, to run the task every 10 seconds for 1 minute:

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);

Another thing to note, is that if you never call get on the Future you never know if the task fails - that means you need another Thread to wait on promise.get so that if an Exception is thrown you know immediately that something has gone wrong.

Then then question is who monitors the monitoring threads . So you quickly find yourself reimplementing a task scheduling library if you want something robust.


Also note the useful utility method Executors.newSingleThreadScheduledExecutor() .

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