1.Spring Framework 自身提供了对定时任务的支持, Spring Boot 中 @Scheduled 定时器的使用。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27@Configuration @EnableScheduling @Slf4j public class Scheduled { @Autowired private CeShiService ceShiService; public static Map<String,Long> xinTiaoMap = new HashMap<>(); public static void addXinTiaoMap(Map map){ xinTiaoMap.putAll(map); }; @Scheduled(fixedRate = 60*1000*5) //5分钟执行一次,只要服务启动会自动执行 public void xintiao(){ for (String key : xinTiaoMap.keySet()) { long value = xinTiaoMap.get(key); QueryWrapper queryWrapper = new QueryWrapper(); queryWrapper.eq("type", "定时任务"); queryWrapper.eq("ip", key); Devices devices = ceShiService.getOne(queryWrapper); try { if (devices != null) { long currentMilliSeconds = System.currentTimeMillis();//当前系统毫秒值 System.out.println("currentMilliSeconds-xintiaoMilliSeconds==" + (currentMilliSeconds - value)); } catch (Exception e) { e.getMessage(); } } }
2.启动时调用定时任务执行
复制代码
1
2
3
4
5
6@Component public class Init implements CommandLineRunner {//平常开发中有可能需要实现在项目启动后执行的功能,SpringBoot提供的一种简单的实现方案就是添加一个model并实现CommandLineRunner接口,实现功能的代码放在实现的run方法中 @Override public void run(String... args) throws Exception { TimedTask();//定时任务 }
复制代码
1
2
3
4
5
6
7
8public void TimedTask(){ // 创建任务队列 ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10); // 10 为线程数量 // 执行任务 scheduledExecutorService.scheduleAtFixedRate(() -> { System.out.println("定时任务已执行"); }, 1, 120, TimeUnit.SECONDS); // 1s 后开始执行,每 2分钟(120秒) 执行一次 }
复制代码
1}
最后
以上就是大方银耳汤最近收集整理的关于java 定时启动 SpringBoot+Scheduled 和CommandLineRunner的全部内容,更多相关java内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复