gpt4 book ai didi

Java:计划任务

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:42 25 4
gpt4 key购买 nike

我有 2 个任务 - 任务 A 和任务 B。任务 A 应该首先执行,完成后,我想启动我的定期任务 B,它会继续执行任务,直到成功。我怎样才能在java中实现这个?我正在研究计划执行服务,但这些服务似乎更多地基于时间而不是任务状态。

最佳答案

这是一种方法:

import java.util.concurrent.*;

public class ScheduledTasks {
public static void main(String[] args) {
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(3);
FollowupTask followupTask = new FollowupTask(executorService);
FirstTask firstTask = new FirstTask(followupTask, executorService);
executorService.submit(firstTask);
}

static class FirstTask implements Runnable {
private FollowupTask followup;
private ScheduledExecutorService executorService;

FirstTask(FollowupTask followup, ScheduledExecutorService executorService) {
this.followup = followup;
this.executorService = executorService;
}

@Override
public void run() {
System.out.println("First task: counting to 5");
for (int i = 1; i <= 5; i++) {
sleep(1000);
System.out.println(i);
}
System.out.println("All done! Submitting followup task.");
executorService.submit(followup);
}
}

static class FollowupTask implements Runnable {
private int invocationCount = 0;
private ScheduledExecutorService executorService;

public FollowupTask(ScheduledExecutorService executorService) {
this.executorService = executorService;
}

@Override
public void run() {
invocationCount++;
if (invocationCount == 1) {
System.out.println("Followup task: resubmit while invocationCount < 20");
}
System.out.println("invocationCount = " + invocationCount);
if (invocationCount < 20) {
executorService.schedule(this, 250, TimeUnit.MILLISECONDS);
} else {
executorService.shutdown();
}
}
}

static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
throw new IllegalStateException("I shouldn't be interrupted!", e);
}
}
}

关于Java:计划任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7775622/

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