springboot 定时任务 implements Job 开发。

1、在 application.properties 中配置要实例化的类

#quartz
quartz.scheduler.instanceName:b2bScheduler
2、定时任务配置类


@Configuration
public class QuarzConfig {
    @Value("${quartz.scheduler.instanceName}")
    private String quartzInstanceName;

    @Value("${spring.datasource.driverClassName}")
    private String myDSDriver;

    @Value("${spring.datasource.url}")
    private String myDSURL;

    @Value("${spring.datasource.username}")
    private String myDSUser;

    @Value("${spring.datasource.password}")
    private String myDSPassword;

    private Properties quartzProperties() throws IOException {
        Properties prop = new Properties();
        prop.put("quartz.scheduler.instanceName", quartzInstanceName);
        prop.put("org.quartz.scheduler.instanceId", "AUTO");
        prop.put("org.quartz.scheduler.skipUpdateCheck", "true");
        prop.put("org.quartz.scheduler.jmx.export", "true");

        prop.put("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX");
        prop.put("org.quartz.jobStore.driverDelegateClass", "org.quartz.impl.jdbcjobstore.StdJDBCDelegate");
        prop.put("org.quartz.jobStore.dataSource", "myDS");
        prop.put("org.quartz.jobStore.tablePrefix", "qrtz_");
        prop.put("org.quartz.jobStore.isClustered", "true");

        prop.put("org.quartz.jobStore.clusterCheckinInterval", "20000");
        prop.put("org.quartz.jobStore.maxMisfiresToHandleAtATime", "1");
        prop.put("org.quartz.jobStore.misfireThreshold", "120000");
        prop.put("org.quartz.jobStore.txIsolationLevelSerializable", "true");
        prop.put("org.quartz.jobStore.selectWithLockSQL", "SELECT * FROM {0}LOCKS WHERE LOCK_NAME = ? FOR UPDATE");

        prop.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
        prop.put("org.quartz.threadPool.threadCount", "10");
        prop.put("org.quartz.threadPool.threadPriority", "5");
        prop.put("org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread", "true");

        prop.put("org.quartz.dataSource.myDS.driver", myDSDriver);
        prop.put("org.quartz.dataSource.myDS.URL", myDSURL);
        prop.put("org.quartz.dataSource.myDS.user", myDSUser);
        prop.put("org.quartz.dataSource.myDS.password", myDSPassword);

        prop.put("org.quartz.plugin.triggHistory.class", "org.quartz.plugins.history.LoggingJobHistoryPlugin");
        prop.put("org.quartz.plugin.shutdownhook.class", "org.quartz.plugins.management.ShutdownHookPlugin");
        prop.put("org.quartz.plugin.shutdownhook.cleanShutdown", "true");
        return prop;
    }


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


    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory) throws IOException {
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        bean.setOverwriteExistingJobs(true);
        bean.setQuartzProperties(quartzProperties());
        bean.setJobFactory(jobFactory);
        bean.setStartupDelay(20);
        return bean;
    }
}

3、Job 工厂

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;
    }
}
4、核心Job 方法。积分清零的任务。每 5 秒执行一次。


@Component
public class ScoreJob implements Job{
    private static final Logger logger = LoggerFactory.getLogger(ScoreJob.class);

    private static final String NAME = "clean_score_job";//正式
    private static final String CRON = "0/5 * * * * ?";//正式

    @Autowired
   @Qualifier("schedulerFactoryBean")
    private Scheduler b2bScheduler;
    @PostConstruct
    public void init() {
        CronTriggerFactoryBean tigger = new CronTriggerFactoryBean();
        // 构建job信息
        JobDetail jobDetail = JobBuilder.newJob(ScoreJob.class).withIdentity(NAME, NAME).build();
        System.out.println(jobDetail.isConcurrentExectionDisallowed());
        tigger.getJobDataMap().put(NAME, NAME);
        tigger.setJobDetail(jobDetail);
        tigger.setBeanName(NAME);
        try {
            tigger.setCronExpression(CRON);
            tigger.afterPropertiesSet();
            JobKey jobKey = new JobKey(NAME, NAME);
            boolean checkExists = b2bScheduler.checkExists(jobKey);
            if (checkExists) {
                b2bScheduler.deleteJob(jobKey);
            }
            //b2bScheduler.scheduleJob(jobDetail, tigger.getObject());

        } catch (Exception e) {
            logger.error("score job error", e);
        }
    }


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //logger.info("定时任务 年底清零 开始----------");
        //logger.info("定时任务 年底清零 结束----------");

    }
}




©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页