gpt4 book ai didi

一旦他分配的任务之一因任何原因失败,Java 就会停止执行程序服务

转载 作者:行者123 更新时间:2023-12-04 01:03:35 25 4
gpt4 key购买 nike

我需要某种服务,它可以同时运行几个任务,并且以 1 秒的间隔运行 1 分钟。

如果其中一个任务失败,我想停止服务以及与它一起运行的每个任务,并带有某种错误的指示符,否则如果一分钟后一切顺利,服务将停止并显示一切顺利的指示符。

例如,我有 2 个功能:

Runnable task1 = ()->{
int num = Math.rand(1,100);
if (num < 5){
throw new Exception("something went wrong with this task,terminate");
}
}

Runnable task2 = ()->{
int num = Math.rand(1,100)
return num < 50;
}



ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
task1schedule = scheduledExecutorService.scheduleAtFixedRate(task1, 1, 60, TimeUnit.SECONDS);
task2schedule = scheduledExecutorService.scheduleAtFixedRate(task2, 1, 60, TimeUnit.SECONDS);

if (!task1schedule || !task2schedule) scheduledExecutorService.shutdown();

关于我应该如何解决这个问题并使事情尽可能通用的任何想法?

最佳答案

这个想法是任务正在推送到一个公共(public)对象TaskCompleteEvent。如果他们推送错误,调度程序将停止,所有任务都将停止。

您可以在 map “错误”和“成功”中检查每个任务迭代的结果。

public class SchedulerTest {

@Test
public void scheduler() throws InterruptedException {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
TaskCompleteEvent taskCompleteEvent = new TaskCompleteEvent(scheduledExecutorService);
Runnable task1 = () -> {
int num = new Random().nextInt(100);
if (num < 5) {
taskCompleteEvent.message("task1-"+UUID.randomUUID().toString(), "Num "+num+" was obatined. Breaking all the executions.", true);
}
};
Runnable task2 = () -> {
int num = new Random().nextInt(100);
taskCompleteEvent.message("task2-"+UUID.randomUUID().toString(), num < 50, false);
};
scheduledExecutorService.scheduleAtFixedRate(task1, 0, 1, TimeUnit.SECONDS);
scheduledExecutorService.scheduleAtFixedRate(task2, 0, 1, TimeUnit.SECONDS);
scheduledExecutorService.awaitTermination(60, TimeUnit.SECONDS);
System.out.println("Success: "+taskCompleteEvent.getSuccess());
System.out.println("Errors: "+taskCompleteEvent.getErrors());
System.out.println("Went well?: "+taskCompleteEvent.getErrors().isEmpty());
}

public static class TaskCompleteEvent {

private final ScheduledExecutorService scheduledExecutorService;
private final Map<String, Object> errors = new LinkedHashMap<>();
private final Map<String, Object> success = new LinkedHashMap<>();

public TaskCompleteEvent(ScheduledExecutorService scheduledExecutorService) {
this.scheduledExecutorService = scheduledExecutorService;
}

public synchronized void message(String id, Object response, boolean error) {
if (error) {
errors.put(id, response);
scheduledExecutorService.shutdown();
} else {
success.put(id, response);
}
}

public synchronized Map<String, Object> getErrors() {
return errors;
}

public synchronized Map<String, Object> getSuccess() {
return success;
}

}

}

关于一旦他分配的任务之一因任何原因失败,Java 就会停止执行程序服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58791345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com