文章目录
- SpringBoot整合定时任务和异步任务
- 定时任务schedule
- 定时任务配置实战
- 异步任务Async
SpringBoot整合定时任务和异步任务
定时任务schedule
什么是定时任务:
- 在预定义的时间点或时间间隔自动执行特定任务的技术
应用场景:
- 数据统计报表生成
- 缓存数据刷新
- 数据备份和清理
- 消息推送
- 系统监控告警
Spring Schedule 优势:
- 注解驱动,配置简单
- 与 Spring 生态完美整合
- 支持 Cron 表达式
- 支持固定速率和固定延迟
定时任务核心注解
| 注解 | 作用 | 示例 |
|---|---|---|
@Scheduled | 标记方法为定时任务 | @Scheduled(cron = "0 0 2 * * ?") |
@EnableScheduling | 启用定时任务功能 | 在配置类上使用 |
定时任务配置方式对比
| 配置方式 | 适用场景 | 优点 | 缺点 |
|---|---|---|---|
| Cron 表达式 | 复杂时间规则 | 功能强大,灵活 | 学习成本较高 |
| 固定速率 | 固定间隔执行 | 简单易用 | 不考虑任务执行时间 |
| 固定延迟 | 任务完成后间隔 | 避免任务重叠 | 间隔时间不固定 |
定时任务配置实战
启动类注解
@SpringBootApplication@EnableScheduling//开启支持定时任务publicclassSsmDemoApplication{publicstaticvoidmain(String[]args){SpringApplication.run(SsmDemoApplication.class,args);}}@Component@Slf4jpublicclassScheduledTaskService{/** * Cron表达式任务 - 每5秒执行一次 * 秒 分 时 日 月 周 */@Scheduled(cron="*/5 * * * * ?")publicvoidcronTask(){log.info("Cron表达式任务执行,时间:{}",LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));}}测试结果
2026-01-19T09:25:00.014+08:00 INFO 1280 --- [ scheduling-1] c.g.service.ScheduledTaskService : Cron表达式任务执行,时间:2026-01-19 09:25:00 2026-01-19T09:25:05.014+08:00 INFO 1280 --- [ scheduling-1] c.g.service.ScheduledTaskService : Cron表达式任务执行,时间:2026-01-19 09:25:05 2026-01-19T09:25:10.003+08:00 INFO 1280 --- [ scheduling-1] c.g.service.ScheduledTaskService : Cron表达式任务执行,时间:2026-01-19 09:25:10 2026-01-19T09:25:15.008+08:00 INFO 1280 --- [ scheduling-1] c.g.service.ScheduledTaskService : Cron表达式任务执行,时间:2026-01-19 09:25:15 2026-01-19T09:25:20.009+08:00 INFO 1280 --- [ scheduling-1] c.g.service.ScheduledTaskService : Cron表达式任务执行,时间:2026-01-19 09:25:20 2026-01-19T09:25:25.004+08:00 INFO 1280 --- [ scheduling-1] c.g.service.ScheduledTaskService : Cron表达式任务执行,时间:2026-01-19 09:25:25 2026-01-19T09:25:30.011+08:00 INFO 1280 --- [ scheduling-1] c.g.service.ScheduledTaskService : Cron表达式任务执行,时间:2026-01-19 09:25:30Cron 表达式详解表格
| 字段 | 允许值 | 允许特殊字符 | 说明 |
|---|---|---|---|
| 秒 | 0-59 | , - * / | 秒字段 |
| 分 | 0-59 | , - * / | 分钟字段 |
| 时 | 0-23 | , - * / | 小时字段 |
| 日 | 1-31 | , - * ? / L W | 日期字段 |
| 月 | 1-12或JAN-DEC | , - * / | 月份字段 |
| 周 | 1-7或SUN-SAT | , - * ? / L # | 星期字段 |
常用Cron表达式示例:
0 0 2 * * ?- 每天凌晨2点执行0 0/5 * * * ?- 每5分钟执行一次0 0 9-18 * * ?- 每天9点到18点整点执行0 0 12 ? * MON-FRI- 周一到周五中午12点执行
异步任务Async
异步任务概念
- 任务的执行不会阻塞主线程
- 任务在后台执行
- 执行完成后通过回调、事件或通知的方式返回结果
@Configuration@EnableAsync//开启执行异步任务publicclassAsyncConfig{@BeanpublicTaskExecutortaskExecutor(){ThreadPoolTaskExecutorexecutor=newThreadPoolTaskExecutor();// 核心线程数executor.setCorePoolSize(5);// 最大线程数executor.setMaxPoolSize(10);// 队列容量executor.setQueueCapacity(100);// 线程名前缀executor.setThreadNamePrefix("async-task-");// 拒绝策略executor.setRejectedExecutionHandler(newThreadPoolExecutor.CallerRunsPolicy());// 等待所有任务结束后再关闭线程池executor.setWaitForTasksToCompleteOnShutdown(true);// 等待时间executor.setAwaitTerminationSeconds(60);executor.initialize();returnexecutor;}}@Service@Slf4jpublicclassAsyncTaskService{/** * 异步任务 */@Async// 标记为异步方法publicvoidsimpleAsyncTask(StringtaskName){log.info("异步任务开始执行:{},线程:{}",taskName,Thread.currentThread().getName());// 模拟任务执行时间try{Thread.sleep(3000);}catch(InterruptedExceptione){Thread.currentThread().interrupt();}log.info("异步任务执行完成:{}",taskName);}}@RestController@Slf4jpublicclassAsyncController{@AutowiredprivateAsyncTaskServiceasyncTaskService;/** * 触发异步任务 */@GetMapping("/async/simple")publicResponseEntity<Map<String,Object>>triggerSimpleAsyncTask(){log.info("接收到异步任务请求,时间:{}",LocalDateTime.now());// 触发异步任务asyncTaskService.simpleAsyncTask("简单异步任务");Map<String,Object>response=newHashMap<>();response.put("code",200);response.put("message","异步任务已触发");response.put("timestamp",LocalDateTime.now());returnResponseEntity.ok(response);}}