计划任务 java,Java:计划任务

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.

解决方案

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

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值