SpringBoot integrates Quartz timing tasks & multiple timing tasks

Reference blog: https://blog.csdn.net/chenmingxu438521/article/details/94485695

https://blog.csdn.net/upxiaofeng/article/details/79415108#commentBox

https://blog.csdn.net/a510750/article/details/90241004

https://blog.csdn.net/qq_29145405/article/details/81843123

 

There are too many SpringBoot related dependencies on the Internet, find it online

JobFactory class

Used to solve the problem that quartz cannot be injected through @Autowired

@Component
public class JobFactory extends AdaptableJobFactory {
	/**
	 * AutowireCapableBeanFactory接口是BeanFactory的子类
	 * 可以连接和填充那些生命周期不被Spring管理的已存在的bean实例
	 */
	private AutowireCapableBeanFactory factory;
	
	public JobFactory(AutowireCapableBeanFactory factory) {
		this.factory = factory;
	}

	/**
	 * 创建Job实例
	 */
	@Override
	protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
		// 实例化对象
		Object job = super.createJobInstance(bundle);
		// 进行注入(Spring管理该Bean)
		factory.autowireBean(job);
		// 返回对象
		return job;
	}
}

SchedulerListener类

@Configuration
public class SchedulerListener implements ApplicationListener<ContextRefreshedEvent> {
	
	@Autowired
    public QuartzProvider quartzProvider;
	
	private JobFactory jobFactory;

    public SchedulerListener (JobFactory jobFactory){
        this.jobFactory = jobFactory;
    }
	
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		try {
			quartzProvider.executeTasks();
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	
	@Bean
    public SchedulerFactoryBean schedulerFactoryBean(){
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setJobFactory(jobFactory);
        return schedulerFactoryBean;
    }
}

QuartzProvider class

@Component
public class QuartzProvider {
	
	// 获取到所有实现了quartzService的接口集合
	@Autowired
	private List<QuartzService> quartzServiceList;

	@Autowired
	SchedulerFactoryBean schedulerFactoryBean;

	/**
	 * @date: 2020年12月22日
	 */
	public void executeTasks() {

		if (!CollectionUtils.isEmpty(quartzServiceList)) {
			String scheduleName = "";
			String cron = "";
			// 对所有实现了quartzServiceList进行遍历,并添加定时任务
			for (int i = 0; i < quartzServiceList.size(); i++) {
				try {
					// 获取到定时任务的cron表达式与scheduleName
					scheduleName = quartzServiceList.get(i).getClass().getName();
					cron = quartzServiceList.get(i).getCron();
					
					JobDetail jobDetail = JobBuilder.newJob(quartzServiceList.get(i).getClass())
							.withIdentity(scheduleName, "group1").build();
					CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
					CronTrigger cronTrigger = getCronTrigger(scheduleBuilder, scheduleName);
					schedulerFactoryBean.getScheduler().scheduleJob(jobDetail, cronTrigger);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 获取一个Trigger的实例,不同的定时任务,分组可以相同,实例名必须不同
	 * @date: 2020年12月22日
	 * @param scheduleBuilder
	 * @param name TriggerBuilder设置定时任务时要求每个定时任务的name不同
	 * @return
	 */
	private CronTrigger getCronTrigger(CronScheduleBuilder scheduleBuilder, String name) {
		return TriggerBuilder.newTrigger().withIdentity(name, "group1")
				.withSchedule(scheduleBuilder).build();
	}

}

Define the interface QuartzService

public interface QuartzService extends Job {
	public String getCron();
}

So far, it has been completed. To write a timed task, you only need to implement the QuartzService interface.

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Below is the test code

Hello class

* The configuration in application.properties here is quartz.test=0/5 * * * *? And the cron expression will be blank after schedule is used. In the test code below, you will see that the configuration configuration will be printed normally for the first time , And then print null

@Component
public class Hello implements QuartzService{
	
    // 这里没有写死,采用的是在配置文件中进行配置的方式,建议写成配置的方式,便于查看
	@Value("${quartz.test}")
	private String cron;
	@Override
	public String getCron() {
		System.out.println(cron);
		System.out.println("cron使用后会被置空:");
		return cron;
	}
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		System.out.println(cron);
	}
}

MyImpl class

@Component
public class MyImpl implements QuartzService{
	@Override
	public String getCron() {
		return "0/1 * * * * ?";
	}
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		System.out.println("bbb");
	}
}

Test effect

Guess you like

Origin blog.csdn.net/qq_26896085/article/details/111503943