在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关联起来,完成了任务的调度。