news 2026/5/29 7:02:58

第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/5/20 10:35:02

如何轻松绕过付费墙:智能内容解锁工具完整使用指南

如何轻松绕过付费墙&#xff1a;智能内容解锁工具完整使用指南 【免费下载链接】bypass-paywalls-chrome-clean 项目地址: https://gitcode.com/GitHub_Trending/by/bypass-paywalls-chrome-clean 你是否曾经遇到过这样的情况&#xff1a;点击一篇感兴趣的文章&#xf…

作者头像 李华
网站建设 2026/5/20 13:48:55

Visual C++运行库终极修复手册:10分钟解决软件兼容性问题

Visual C运行库终极修复手册&#xff1a;10分钟解决软件兼容性问题 【免费下载链接】vcredist AIO Repack for latest Microsoft Visual C Redistributable Runtimes 项目地址: https://gitcode.com/gh_mirrors/vc/vcredist 当您满怀期待地启动新安装的软件时&#xff0…

作者头像 李华
网站建设 2026/5/25 4:36:05

LyricsX:macOS平台快速上手指南与核心功能详解

LyricsX&#xff1a;macOS平台快速上手指南与核心功能详解 【免费下载链接】LyricsX &#x1f3b6; Ultimate lyrics app for macOS. 项目地址: https://gitcode.com/gh_mirrors/lyr/LyricsX LyricsX是macOS系统上功能强大的歌词显示工具&#xff0c;能够智能识别播放中…

作者头像 李华