我有一个定时任务,我不需要它执行的时候能让正在执行的任务停下来
问题图片
我这结束后还是会继续输出1,我需要让它停止的时候就不执行这段代码块的内容了
代码内容
AtomicReference<String> result = new AtomicReference<>("");
CountDownLatch latch = new CountDownLatch(1);
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
Runnable task = () -> {
// 在这里编写发送请求的代码
if (StringUtils.isEmpty(signDTO.getCookie())) {
return;
}
String signList = getSignList(signDTO.getCookie());
Gson gson = new Gson();
SignList signList1 = gson.fromJson(signList, SignList.class);
SignListData[] signListData = signList1.getData();
int signListLengths = signListData.length;
if (signListLengths != signListLength) {
for (SignListData signListData2 : signListData) {
// 未签到
if (signListData2.getType() != 1) {
Long start = signListData2.getStart();
Date date = new Date();
long time = date.getTime();
Sign sign = new Sign(signDTO.getCountry(), signDTO.getProvince(), signDTO.getCity(), signDTO.getDistrict(), signDTO.getStreet(), signDTO.getLatitude(), signDTO.getLongitude());
String response = "";
Response response1 = null;
// 找到今天的数据
if (start >= time) {
// 开始签到
response = sendSign(sign, signDTO.getCookie(), signListData2.getId(), signListData2.getSchoolId(), signListData2.getSignId());
result.set(response);
response1 = gson.fromJson(response, Response.class);
} else {
response = sendSign(sign, signDTO.getCookie(), signListData2.getId(), signListData2.getSchoolId(), signListData2.getSignId());
result.set(response);
response1 = gson.fromJson(response, Response.class);
}
sendMessage("我在校园自动签到助手提醒您", response1.getMessage(), signListData2.getSignTitle(), signListData2.getSignContext(), signDTO.getUid());
}
}
}
signListLength = signListLengths;
latch.countDown();
};
// 设置任务开始的延迟时间(以毫秒为单位,这里为0表示立即执行)
long initialDelay = 0;
// 设置任务的执行间隔时间(以毫秒为单位,这里为1小时)
long interval = 10000;
executor.scheduleAtFixedRate(task, initialDelay, interval, TimeUnit.MILLISECONDS);
latch.await();
System.out.println(result.get());
return result.get();