在Spring框架中,使用Quartz來實現任務延遲主要涉及到以下幾個步驟:
下面是一個簡單的示例代碼,展示了如何在Spring中使用Quartz實現任務延遲執行:
// 1. 配置Quartz
@Configuration
public class QuartzConfig {
@Bean
public JobDetailFactoryBean jobDetail() {
JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
factoryBean.setJobClass(MyJob.class); // 2. 創建Job類
factoryBean.setDurability(true);
return factoryBean;
}
@Bean
public SimpleScheduleBuilder scheduleBuilder() {
return SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(10) // 設置間隔時間
.repeatForever(); // 持續重復
}
@Bean
public CronTriggerFactoryBean trigger(JobDetail jobDetail) {
CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean();
factoryBean.setJobDetail(jobDetail);
factoryBean.setCronExpression("0 0 12 * ?"); // 設置延遲12小時執行一次
return factoryBean;
}
@Bean
public SchedulerFactoryBean scheduler(Trigger trigger) throws Exception {
SchedulerFactoryBean factoryBean = new SchedulerFactoryBean();
factoryBean.setTriggers(trigger);
return factoryBean;
}
}
// 2. 創建Job類
public class MyJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("執行任務:" + new Date());
}
}
在上面的示例中,我們定義了一個名為MyJob的Job類,它實現了Job接口的execute()方法。然后,我們使用SimpleScheduleBuilder類構建了一個觸發器,設置了延遲12小時執行一次的任務調度策略。最后,通過Scheduler的scheduleJob()方法將Job和Trigger關聯起來,完成了任務的調度。