今天项目里要求在某一时间自动触发一些业务,所以想到了Quartz,看了很多网上的文章博客,也遇到了一些坑,所以想记录下来,以后可能也会用到。
1、引入pom依赖
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.2.3</version>
</dependency>
2、Quartz配置 .java文件:
@Configuration
public class QuartzConfig {
@Autowired
private SpringJobFactory springJobFactory;
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean.setJobFactory(springJobFactory);
return schedulerFactoryBean;
}
@Bean
public Scheduler scheduler() {
return schedulerFactoryBean().getScheduler();
}
}
3、创建job实例
@Component
public class SpringJobFactory extends AdaptableJobFactory {
@Autowired
private AutowireCapableBeanFactory capableBeanFactory;
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
Object jobInstance = super.createJobInstance(bundle);
capableBeanFactory.autowireBean(jobInstance);
return jobInstance;
}
}
4、创建scheduler实例
@Service
public class QuartzService {
private static final String JOB_GROUP = "event_job_group";
private static final String TRIGGER_GROUP = "event_trigger_group";
@Autowired
private Scheduler scheduler;
/**
* 创建定时任务
* @param jobDetailName
* @param cronExpression
* @param jobClass
* @throws SchedulerException
*/
public void createScheduleJob(String jobDetailName, String cronExpression, Class<? extends Job> jobClass) throws SchedulerException {
JobDetail jobDetail = JobBuilder.newJob(jobClass)
.withIdentity("task_" + jobDetailName, JOB_GROUP).storeDurably().requestRecovery().build();
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("task_" + jobDetailName, TRIGGER_GROUP).withSchedule(scheduleBuilder).build();
scheduler.scheduleJob(jobDetail, trigger);
}
}
5、创建job:写具体的业务逻辑
public class CancelOrderJob implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//业务逻辑处理
System.out.println("具体业务逻辑");
}
}
6、创建spring监听:项目启动就开始执行
@Configuration
public class ApplicationStartQuartzJobListener implements ApplicationListener<ContextRefreshedEvent> {
private static Logger LOG = LoggerFactory.getLogger(ApplicationStartQuartzJobListener.class);
@Autowired
private QuartzService quartzService;
/**
* 初始启动quartz
*/
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
try {
//30分钟自动取消订单任务
quartzService.createScheduleJob("cancelOrderTask", "0 0/1 * * * ? ", CancelOrderJob.class);
LOG.info("任务已经启动...");
} catch (SchedulerException e) {
LOG.error(e.getMessage());
}
}
7、写完具体逻辑后运行效果
image.png
网友评论