千峰商城-springboot项目搭建-85-订单超时取消-定时任务框架quartz的整合使用
1.创建新的springboot项目

2.导入依赖
删除多余文件
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency>
3.创建定时任务
定时任务:每隔指定的时间就执行一次任务。案例:每隔三秒打印一次helloworld。
创建一个service包:
创建PrintHelloWorldJob类:
可以生成Scheduled中的定时语法的定时器网址:https://cron.qqe2.com/
PrintHelloWorldJob :
@Component public class PrintHelloWorldJob { //https://cron.qqe2.com //生成器,可以生成Scheduled中的定时语法 @Scheduled(cron = "0/3 * * * * ?") public void printHelloWorld(){ System.out.println("----------HelloWorld."); } }
Scheduled中的定时语法:
字段 | * | * | * | * | * | * |
含义 | 秒 | 分 | 小时 | 日 | 月 | 星期 |
取值 | 0-59 | 0-59 | 0-23 | 1-31 |
1-12或月份对应的 前三个英文字母(大小写均可) |
0-7(0、7表示周日)或星期对应的 前三个英文字母(大小写均可) |
允许的特殊字符 | , - * / | , - * / | , - * / | , - * / ? L | , - * / | , - * / ? L |
特殊字符含义:
特殊字符 | , | - | * | / | ? | L |
含义 | 枚举 | 区间 | 任意值 | 步长 | 日/星期冲突匹配符 | 最后 |
举例 |
"1,3,5 * * * * *" 任意时间的1、3、5秒钟执行 |
"0 0-5 14 * * ?" 每天14:00-14:05触发 |
"0 0 12 * * ?" 每天12:00触发 |
"0/5 * * * * *" 每5秒触发一次 |
"0 * * 26 * ?" 每月的26日的每分钟执行 |
"0 0 * L * ?" 每月最后一日的每一小时执行 |
application.properties:(由于商城项目已占用8080端口,所以修改新项目的端口为9999)
server.port=9999
在启动类上添加注解@EnableScheduling,启动定时任务:
@SpringBootApplication @EnableScheduling public class QuartzDemoApplication { public static void main(String[] args) { SpringApplication.run(QuartzDemoApplication.class, args); } }
启动api,进行测试:
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性