Using Quartz with Spring Boot, you can spring-boot-starter-quartz
simplify configuration by adding dependencies. Below is a simple example showing how to use Quartz in a Spring Boot application.
- First,
pom.xml
addspring-boot-starter-quartz
dependencies to the file:
<dependencies>
...
dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
...
</dependencies>
- Create a Quartz Job class. This class needs to implement
org.quartz.Job
the interface and implementexecute
the methods:
import org.quartz.Job;
org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class MyJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("Hello, Quartz!");
}
}
- Configure Quartz in the Spring Boot configuration class:
import org.quartz.JobDetail;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;
@Configuration
public class QuartzConfig {
@Bean
public JobDetailFactoryBean myJobDetail() {
JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean();
jobDetailFactoryBean.setJobClass(MyJob.class);
jobDetailFactoryBean.setDurability(true);
return jobDetailFactoryBean;
}
@Bean
public SimpleTriggerFactoryBean myJobTrigger(JobDetail myJobDetail) {
SimpleTriggerFactoryBean trigger = new SimpleTriggerFactoryBean();
trigger.setJobDetail(myJobDetail);
trigger.setRepeatInterval(5000); // 每5秒执行一次
trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY); // 无限次重复
return trigger;
}
}
In this example, we create a simple Quartz Job that executes every 5 seconds.
Regarding Quartz's cron expression, it is a string containing 6 or 7 fields that is used to define the execution time of the task. The order of the fields is: seconds, minutes, hours, day of month, month, day of week (optional).
Here are some examples of cron expressions:
0 0 * * * *
: Execution on the hour every hour*/10 * * * *
: Executed every 10 seconds0 0 8-10 * * *
: Executed at 8:00, 9:00 and 10:00 every day0 0 6,19 * * *
: Executed at 6:00 AM and 7:00 PM every day00/30 8-10 * * *
: 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day0 0 9-17 * * MON-FRI
: Executed every hour from 9:00 to 17:00 on weekdays0 0 0 25 12 ?
: Executed every Christmas at midnight
For more information about Quartz cron expressions, you can refer to the official article: Quartz CronTrigger Tutorial .