在Spring中使用Quartz,需要进行以下步骤:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
org.quartz.Job
接口的Job类,实现具体的定时任务逻辑。public class MyJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
// 定时任务逻辑
}
}
org.springframework.scheduling.quartz.JobDetailFactoryBean
和org.springframework.scheduling.quartz.SimpleTriggerFactoryBean
分别创建JobDetail和Trigger。<bean id="myJobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.example.MyJob" />
</bean>
<bean id="myTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
<property name="jobDetail" ref="myJobDetail" />
<property name="repeatInterval" value="10000" /> <!-- 每10秒执行一次 -->
</bean>
org.springframework.scheduling.quartz.SchedulerFactoryBean
创建SchedulerFactoryBean,将JobDetail和Trigger添加到Scheduler中。<bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="myTrigger" />
</list>
</property>
</bean>
@EnableScheduling
注解启用定时任务,并在@Scheduled
注解的方法中添加定时任务的逻辑。@EnableScheduling
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Scheduled(cron = "0 0/1 * * * ?") // 每分钟执行一次
public void cronJob() {
// 定时任务逻辑
}
}
以上就是在Spring中使用Quartz的基本步骤。可以根据具体的需求进行配置和定制化。