springBoot整合quartz(多任务)

配置文件******************************
sync:
  organization:
    cron: 0 0 0/1 * * ?
quartz:

  enabled: true


定义工厂类********************************
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;


public class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {

  private transient AutowireCapableBeanFactory beanFactory;

  @Override
  public void setApplicationContext(final ApplicationContext context) {
    beanFactory = context.getAutowireCapableBeanFactory();
  }

  @Override
  protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
    final Object job = super.createJobInstance(bundle);
    beanFactory.autowireBean(job);
    return job;
  }
}


初始化***************************************
import com.shanlinjinrong.oa.job.SyncOrganizationDataJob;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;


@Configuration
public class QuartzInit implements ApplicationListener {
  private static final Logger LOGGER = LoggerFactory.getLogger(QuartzInit.class);

  @Autowired
  private SchedulerFactoryBean schedulerFactory;

  @Value("${sync.organization.cron}")
  public String cronExpression;

  private static final String JOB_GROUP = "organization-data";

  @Override
  public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
    Scheduler scheduler = schedulerFactory.getScheduler();
    Map> map = new HashMap<>();
    JobDetail authorJobDetail = newJob(SyncOrganizationDataJob.class)
      .withIdentity(SyncOrganizationDataJob.class.getSimpleName(), JOB_GROUP)
      .build();
    // Trigger the job to run now
    Trigger authorReportTrigger = newTrigger()
      .withIdentity(SyncOrganizationDataJob.class.getSimpleName(), JOB_GROUP)
      .startNow()
      .withSchedule(
        cronSchedule(cronExpression)
      )
      .build();
    map.put(authorJobDetail, toSet(authorReportTrigger));

    try {
      scheduler.scheduleJobs(map, true);
    } catch (SchedulerException e) {
      LOGGER.error("初始化JOB发生异常", e);
    }
  }

  private Set toSet(Trigger trigger) {
    Set result = new HashSet<>();
    result.add(trigger);

    return result;
  }
}




Java配置*****************************

import com.shanlinjinrong.oa.conf.factory.AutowiringSpringBeanJobFactory;
import com.shanlinjinrong.oa.job.SyncOrganizationDataJob;
import liquibase.integration.spring.SpringLiquibase;
import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;


@Configuration
@ConditionalOnProperty(name = "quartz.enabled")
public class SchedulerConfig {

  @Bean
  public JobFactory jobFactory(ApplicationContext applicationContext, SpringLiquibase springLiquibase) {
    AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
    jobFactory.setApplicationContext(applicationContext);
    return jobFactory;
  }

  @Bean
  public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource, JobFactory jobFactory) throws IOException {
    SchedulerFactoryBean factory = new SchedulerFactoryBean();
    // this allows to update triggers in DB when updating settings in config file:
    factory.setOverwriteExistingJobs(true);
    factory.setDataSource(dataSource);
    factory.setJobFactory(jobFactory);
    factory.setQuartzProperties(quartzProperties());

    return factory;
  }

  @Bean
  public Properties quartzProperties() throws IOException {
    PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
    propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
    propertiesFactoryBean.afterPropertiesSet();
    return propertiesFactoryBean.getObject();
  }

  @Bean
  public JobDetailFactoryBean standardJobDetail() {
    return createJobDetail(SyncOrganizationDataJob.class);
  }

  private static JobDetailFactoryBean createJobDetail(Class jobClass) {
    JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
    factoryBean.setJobClass(jobClass);
    factoryBean.setDurability(true);
    return factoryBean;
  }
}




Job*execute方法执行job************************************
import com.shanlinjinrong.oa.dmp.GroupStructureDmp;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

@DisallowConcurrentExecution
public class SyncOrganizationDataJob implements Job {

  @Autowired
  private GroupStructureDmp groupStructureDmp;

  @Override
  public void execute(JobExecutionContext context) throws JobExecutionException {
    groupStructureDmp.getDmpData();
  }
}

你可能感兴趣的:(quartz)