preface

When a scheduled task is performed, the service logic of a Job relies on that of other services to complete the task.

When using Quartz, Job creation is new, so using @autowired auto-assembly annotations on Job is invalid.

To enable automatic assembly in jobs, you need to customize factories for jobs.

start

Step 1: Customize the Job Factory class

    /** * Custom Job factory class * 

* Job initialization quartz is new when executed. Spring's management, unable to inject related rely on bean * so need in the job is created using AutowireCapableBeanFactory automatic ZhuanPei job instance * < p > * AutowireCapableBeanFactory, You can use this interface to automatically assemble bean instances */ that are not under Spring's control

@Component public class AutowireJobFactory extends AdaptableJobFactory { @Autowired private AutowireCapableBeanFactory capableBeanFactory; @Override protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { Object jobInstance = super.createJobInstance(bundle); // Automatic assembly example capableBeanFactory.autowireBean(jobInstance); returnjobInstance; }}Copy the code

Step 2: Configure

    @Configuration
    public class QuartzConfig {
        // Customize the Job factory class
        @Autowired
        private ConvertJobFactory convertJobFactory;

        @Bean
        public SchedulerFactoryBean schedulerFactory(a) {
            SchedulerFactoryBean bean = new SchedulerFactoryBean();
            bean.setJobFactory(convertJobFactory);
            returnbean; }}Copy the code

Step 3: Add a utility class to the Quartz task

    @Component
    public class QuartzManager {
        @Autowired
        private SchedulerFactoryBean schedulerFactory;

        public void addJob(Class<? extends Job> jobClass, String jobName, String groupName, String cron) {
            try {
                // Create jobDetail instance and bind the Job implementation class
                // Specify the name of the job, the name of the group to which it belongs, and the binding of the job class
                JobDetail jobDetail = JobBuilder.newJob(jobClass)
                        .withIdentity(jobName, groupName) // The task name and group form the task key
                        .build();
                // Define scheduling trigger rules
                // Use cornTrigger rules
                Trigger trigger = TriggerBuilder.newTrigger()
                        .withIdentity(jobName, groupName)// Trigger key
                        .startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.SECOND))
                        .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                        .startNow().build();

                Scheduler scheduler = schedulerFactory.getScheduler();
                // Register jobs and triggers with the task scheduler
                scheduler.scheduleJob(jobDetail, trigger);
                / / start
                if (!scheduler.isShutdown()) {
                    scheduler.start();
                }
            } catch(SchedulerException e) { e.printStackTrace(); }}}Copy the code

Step 4: Write the Job

    @Component
    public class Cad2ImgConvertQuartz implements Job.InitializingBean {
        @Autowired
        private QuartzManager quartzManager;

        /** * The Job class needs to implement the method in this scenario to implement the task business logic */
        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            //TODO business logic
        }

        /** * InitializingBean class needs to implement a method to be executed after the service is initialized. After service initialization, add Job to task scheduler
        @Override
        public void afterPropertiesSet(a) throws Exception {
			// Add the current task
			quartzManager.addJob(this.getClass(),
			this.getClass().getSimpleName(), QuartzConfig.GROUP_NAME, QuartzConfig.cron); }}Copy the code

That completes the way the Bean is injected, adding quartz dynamically