在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的基本步驟。可以根據具體的需求進行配置和定制化。