Quartz 实现定时任务
初始化配置
添加依赖:
1<!--定时任务 -->
2<dependency>
3 <groupId>org.springframework.boot</groupId>
4 <artifactId>spring-boot-starter-quartz</artifactId>
5</dependency>
主启动类添加 @EnableScheduling
注解。
创建任务
1// TestTask1.java
2public class TestTask1 extends QuartzJobBean {
3 @Override
4 protected void executeInternal(JobExecutionContext context) {
5 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
6 System.out.println("Test1---" + sdf.format(new Date()));
7 }
8}
1// TestTask2.java
2public class TestTask2 extends QuartzJobBean {
3 @Override
4 protected void executeInternal(JobExecutionContext context) {
5 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
6 System.out.println("Test2---" + sdf.format(new Date()));
7 }
8}
配置任务
注意同组下同名任务不会重复执行。
- JobDetail:配置任务信息,生成任务
- Trigger:配置触发器信息,设置时间
1// QuartzConfig.java
2@Configuration
3public class QuartzConfig {
4 @Bean
5 public JobDetail testJ1() {
6 return JobBuilder.newJob(TestTask1.class).withIdentity("job1", "group").storeDurably().build();
7 }
8
9 @Bean
10 public JobDetail testJ2() {
11 return JobBuilder.newJob(TestTask2.class).withIdentity("job2", "group").storeDurably().build();
12 } // "job2" 如果为 "job1",则不会执行 TestTask2 而是执行 TestTask1
13
14 @Bean
15 public Trigger test1() {
16 SimpleScheduleBuilder ssb = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(59).repeatForever();
17 return TriggerBuilder.newTrigger().forJob(testJ1())
18 .withIdentity("trigger1", "group")
19 .withSchedule(ssb)
20 .build();
21 }
22
23 @Bean
24 public Trigger test2() {
25 return TriggerBuilder.newTrigger().forJob(testJ2())
26 .withIdentity("trigger2", "group")
27 .withSchedule(CronScheduleBuilder.cronSchedule("0/59 * * * * ?"))
28 .build();
29 }
30}