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