java spring动态生成定时任务

入口类 DemoApplication.java

 1 package com.example.demo;
 2 
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.SpringBootApplication;
 5 import org.springframework.scheduling.annotation.EnableScheduling;
 6 
 7 @SpringBootApplication
 8 @EnableScheduling
 9 public class DemoApplication {
10 
11     public static void main(String[] args) {
12         SpringApplication.run(DemoApplication.class, args);
13     }
14 
15 }

方式一:

使用SchedulingConfigurer接口

 1 package com.example.demo;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.jdbc.core.JdbcTemplate;
 5 import org.springframework.scheduling.annotation.SchedulingConfigurer;
 6 import org.springframework.scheduling.config.ScheduledTaskRegistrar;
 7 import org.springframework.stereotype.Component;
 8 
 9 import java.util.ArrayList;
10 import java.util.List;
11 
12 @Component
13 public class ScheduleTask implements SchedulingConfigurer {
14     @Autowired
15     private JdbcTemplate jdbcTemplate;
16 
17 
18     @Override
19     public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
20         /**
21          *  模拟从数据库记录中生成相应的定时任务
22          */
23         List<String> tasks = new ArrayList<>();
24         jdbcTemplate.query("select * from demo", rs -> {
25             System.out.println(rs.getString("msg"));
26             tasks.add(rs.getString("msg"));
27         });
28         System.out.println(".... task....");
29         tasks.forEach(s -> {
30             System.out.println(s);
31             scheduledTaskRegistrar.addCronTask(() -> {
32                 System.out.println(s);
33             }, "0/5 * * * * ?");
34         });
35 
36     }
37 }

方式二:

使用ThreadPoolTaskScheduler类

 1 package com.example.demo;
 2 
 3 import org.springframework.boot.CommandLineRunner;
 4 import org.springframework.core.annotation.Order;
 5 import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
 6 import org.springframework.scheduling.support.CronTrigger;
 7 import org.springframework.stereotype.Component;
 8 
 9 import java.util.concurrent.ScheduledFuture;
10 
11 
12 /*
13  * 启动时初始化/准备
14  * Runtime.getRuntime().exec("shutdown -s -t 60")
15  * InetAddress.getByName("192.168.3.240").isReachable(6000)
16  */
17 @Component
18 @Order(1)
19 public class CommonStarting implements CommandLineRunner {
20     @Override
21     public void run(String... args) throws Exception {
22         System.out.println("<<<<<<<<<<<<<<<<<starting application...<<<<<<<<<<<<<<<");
23 
24         ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
25         scheduler.initialize();
26         final ScheduledFuture<?> future = scheduler.schedule(() -> {
27             System.out.println("hello..... from threadPoolTaskScheduler");
28         }, new CronTrigger("*/10 * * * * *"));
29 
30     }
31 }
原文地址:https://www.cnblogs.com/zward/p/13235715.html