定时调度

SpringBoot

# 定时调度

在企业项目开发中,定时调度是一项重要的技术组成,利用定时调度可以帮助用户实现无人值守程序执行,在Spring中提供了简单的SpringTask调度执行任务,利用此组件可以实现间隔调度与CRON调度处理。

# 创建调度类

定义一个线程调度类。

@Component
public class MySchedulerTask {

    @Scheduled(fixedRate = 2000)                // 采用间隔调度,每2秒执行一次
    public void runJobA() {                    // 定义一个要执行的任务
        System.out.println("【*** MyTaskA - 间隔调度 ***】"
                + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
                .format(new Date()));
    }

    @Scheduled(cron = "* * * * * ?")            // 每秒调用一次
    public void runJobB() {
        System.err.println("【*** MyTaskB - 间隔调度 ***】"
                + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
                .format(new Date()));
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 创建自定义线程池

为了让多个任务并行执行,还需要建立一个定时调度池的配置类。

@Configuration            // 定时调度的配置类一定要实现指定的父接口
public class SchedulerConfig implements SchedulingConfigurer {
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {        // 开启线程调度池
        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(10));    // 10个线程池
    }
}
1
2
3
4
5
6
7

# 启动类开启调度

在程序启动类上追加定时任务配置注解。

@SpringBootApplication   // 启动SpringBoot程序,而后自带子包扫描
@EnableScheduling    // 启用调度
public class SpringBootIntegrationSchedulerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootIntegrationSchedulerApplication.class, args);
    }

}
1
2
3
4
5
6
7
8
9

本程序同时启动了两个定时调度,为了使两个线程调度之间不受影响,开辟了一个线程池,可以并行执行多个任务。

打印结果

【*** MyTaskB - 间隔调度 ***】2025-02-23 21:17:25.016
【*** MyTaskB - 间隔调度 ***】2025-02-23 21:17:26.025
【*** MyTaskA - 间隔调度 ***】2025-02-23 21:17:26.336
【*** MyTaskB - 间隔调度 ***】2025-02-23 21:17:27.011
【*** MyTaskB - 间隔调度 ***】2025-02-23 21:17:28.001
【*** MyTaskA - 间隔调度 ***】2025-02-23 21:17:28.332
【*** MyTaskB - 间隔调度 ***】2025-02-23 21:17:29.005
【*** MyTaskB - 间隔调度 ***】2025-02-23 21:17:30.003
【*** MyTaskA - 间隔调度 ***】2025-02-23 21:17:30.331
【*** MyTaskB - 间隔调度 ***】2025-02-23 21:17:31.004
【*** MyTaskB - 间隔调度 ***】2025-02-23 21:17:32.149
【*** MyTaskA - 间隔调度 ***】2025-02-23 21:17:32.325
【*** MyTaskB - 间隔调度 ***】2025-02-23 21:17:33.003
【*** MyTaskB - 间隔调度 ***】2025-02-23 21:17:34.004
【*** MyTaskA - 间隔调度 ***】2025-02-23 21:17:34.331
【*** MyTaskB - 间隔调度 ***】2025-02-23 21:17:35.007
【*** MyTaskB - 间隔调度 ***】2025-02-23 21:17:36.012
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
最近修改于: 2025/2/25 00:12:34
和宇宙温柔的关联
房东的猫