java - 用于检查可用性的调度程序 Spring
问题描述
我需要向站点发送请求并获取数据,但它们可能还没有准备好。我正在考虑通过@Scheduled 解决这个问题。但问题是成功收货后,我不得不停止请求。这是正确的方法吗?如果是这样,如何终止@Scheduled任务
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
ResponseEntity<String> response
= restTemplate.getForEntity(Url , String.class);
}
解决方案
是的,可以做到。您可以使用ScheduledAnnotationBeanPostProcessor。得到成功响应后,可以调用该类的postProcessBeforeDestruction()方法。这是一个示例:
public class Scheduler {
private final ScheduledAnnotationBeanPostProcessor processor;
private final ApplicationContext context;
@Autowired
public Scheduler(ScheduledAnnotationBeanPostProcessor processor, ApplicationContext context) {
this.processor = processor;
this.context = context;
}
@Scheduled(fixedRate = 5000)
public void doSchedule() {
Random random = new Random();
final int i = random.nextInt() % 5;
// here you will put your logic to call the the stopScheduler()
if (i == 3) {
stopScheduler();
}
}
private void stopScheduler() {
Scheduler bean = context.getBean(Scheduler.class);
processor.postProcessBeforeDestruction(bean, "someString");
log.debug("Scheduler closed!");
}
}
推荐阅读
- python-3.x - 如何在python中使用for循环打开文件
- python - 如何递归遍历列表
- jquery - 使用 JQuery 可以获取 img.show() 的 ID 吗?
- mysql - 我如何“加入”但在 MySQL 的表中保持独立?
- sql - Postgresql - 组内的最小/最大日期范围
- entity-framework - Microsoft.AspNetCore.Identity.IdentityError:“无效用户名”
- javascript - Google 脚本 - 表单:以编程方式处理上传字段:如何获取多个链接?什么都没有上传时如何处理“未定义”?
- regex - 如何为以下匹配创建正则表达式
- python - Python - 跨多个模块与 GUI 元素交互
- tinymce - Tinymce:在编辑器之外创建一个自定义工具栏,如图所示