news 2026/3/6 3:56:14

第7章:SpringBoot整合定时任务和异步任务

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
第7章:SpringBoot整合定时任务和异步任务

文章目录

  • 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:30

Cron 表达式详解表格

字段允许值允许特殊字符说明
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);}}
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/3/1 11:20:54

无名杀网页版:5分钟开启你的三国杀新时代

无名杀网页版&#xff1a;5分钟开启你的三国杀新时代 【免费下载链接】noname 项目地址: https://gitcode.com/GitHub_Trending/no/noname 还在为传统三国杀复杂的安装过程而头疼吗&#xff1f;无名杀网页版为你带来革命性的游戏体验&#xff01;这款开源的三国杀实现让…

作者头像 李华
网站建设 2026/3/4 1:38:34

Linux: gdb-minimal

现在gdb退出了最小化的gdb安装包&#xff0c;依赖的库变少了。gdb-minimal-16.3-2.el9.x86_64。方便了开发者使用&#xff0c;不用再自己单独build gdb了。 URL : https://gnu.org/software/gdb/ Summary : A GNU source-level debugger for C, C, Fortran, Go and…

作者头像 李华
网站建设 2026/3/4 1:08:08

如何快速配置实时通知:B站抢票脚本的完整使用指南

如何快速配置实时通知&#xff1a;B站抢票脚本的完整使用指南 【免费下载链接】biliTickerBuy b站 会员购 抢票 漫展 脚本 bilibili 图形化 纯接口 验证码预演练习 项目地址: https://gitcode.com/GitHub_Trending/bi/biliTickerBuy 你是否曾经因为错过B站会员购门票的开…

作者头像 李华
网站建设 2026/3/5 14:39:38

AI自动化测试实战指南:5个常见问题与高效解决方案

AI自动化测试实战指南&#xff1a;5个常见问题与高效解决方案 【免费下载链接】midscene Let AI be your browser operator. 项目地址: https://gitcode.com/GitHub_Trending/mid/midscene 你是否曾经遇到过这些困扰&#xff1f;花了大量时间编写测试脚本&#xff0c;却…

作者头像 李华