问题
I have 2 tasks - Task A and Task B. Task A should execute first and on completion, I want to start my periodic Task B which keeps doing a task until it becomes success. How can I implement this in java? I was looking at scheduled execution services but those seem to be more time based rather than state of a task.
回答1:
Here's one way:
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);
}
}
}
来源:https://stackoverflow.com/questions/7775622/java-scheduled-tasks