标签:sso 返回结果 运行 org 框架 fir 抛出异常 定时 stat
quartz是一个开源的定时任务框架,具备将定时任务持久化至数据库以及分布式环境下多节点调度的能力。当当的elastic-job便是以quartz为基础,结合zookeeper开发出来的一款产品。
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> <version>2.3.0</version> </dependency>
1 /** 2 * 分布式定时任务quartz配置 3 * Created by chenjunyi on 2018/6/6. 4 */ 5 @Configuration 6 public class QuartzConfiguration { 7 8 /** 9 * quartz的JobFactory,根据注册的JobClass从spring应用上下文中获取job实例 10 */ 11 public static class AutoSpringBeanJobFactory extends AdaptableJobFactory implements SchedulerContextAware { 12 13 /** spring应用上下文 */ 14 private ApplicationContext applicationContext; 15 16 /** scheduler上下文 */ 17 private SchedulerContext schedulerContext; 18 19 /** 需要忽略的属性 */ 20 private String[] ignoredUnknownProperties = null; 21 22 private void setApplicationContext(ApplicationContext applicationContext) { 23 this.applicationContext = applicationContext; 24 } 25 26 @Override 27 public void setSchedulerContext(SchedulerContext schedulerContext) { 28 this.schedulerContext = schedulerContext; 29 } 30 31 private void setIgnoredUnknownProperties(String... ignoredUnknownProperties) { 32 this.ignoredUnknownProperties = ignoredUnknownProperties; 33 } 34 35 @Override 36 protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception { 37 //获取定时任务的clazz,并从spring上下文中获取实例 38 Class<? extends Job> clazz = bundle.getJobDetail().getJobClass(); 39 Job job = applicationContext.getBean(clazz); 40 41 if (isEligibleForPropertyPopulation(job)) { 42 //非继承自QuartzJobBean的Job,设置job属性 43 BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(job); 44 MutablePropertyValues pvs = new MutablePropertyValues(); 45 if (this.schedulerContext != null) { 46 pvs.addPropertyValues(this.schedulerContext); 47 } 48 pvs.addPropertyValues(bundle.getJobDetail().getJobDataMap()); 49 pvs.addPropertyValues(bundle.getTrigger().getJobDataMap()); 50 if (this.ignoredUnknownProperties != null) { 51 for (String propName : this.ignoredUnknownProperties) { 52 if (pvs.contains(propName) && !bw.isWritableProperty(propName)) { 53 pvs.removePropertyValue(propName); 54 } 55 } 56 bw.setPropertyValues(pvs); 57 } else { 58 bw.setPropertyValues(pvs, true); 59 } 60 } 61 return job; 62 } 63 64 private boolean isEligibleForPropertyPopulation(Object jobObject) { 65 return (!(jobObject instanceof QuartzJobBean)); 66 } 67 68 } 69 70 /** 71 * 配置任务工厂实例 72 * @param applicationContext spring上下文实例 73 * @return 任务工厂实例 74 */ 75 @Bean 76 public JobFactory jobFactory(ApplicationContext applicationContext) { 77 AutoSpringBeanJobFactory jobFactory = new AutoSpringBeanJobFactory(); 78 jobFactory.setApplicationContext(applicationContext); 79 return jobFactory; 80 } 81 82 /** 83 * 配置任务调度器,使用项目数据源作为quartz数据源 84 * @param jobFactory 自定义配置任务工厂 85 * @param dataSource 数据源实例 86 * @return 任务调度器 87 */ 88 @Bean 89 public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory, DataSource dataSource) { 90 SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); 91 //将spring管理job自定义工厂交由调度器维护 92 schedulerFactoryBean.setJobFactory(jobFactory); 93 //设置覆盖已存在的任务(配置已失效,因为改写了原有的注册方式,JOB注册时便已自动进行替换) 94 schedulerFactoryBean.setOverwriteExistingJobs(true); 95 //项目启动完成后,等待50秒后开始执行调度器初始化(需要小于JOB的间隔时间) 96 schedulerFactoryBean.setStartupDelay(50); 97 //设置调度器自动运行 98 schedulerFactoryBean.setAutoStartup(true); 99 //设置数据源,使用与项目统一数据源 100 schedulerFactoryBean.setDataSource(dataSource); 101 //设置定时调度器命名空间 102 schedulerFactoryBean.setSchedulerName("MY-QUARTZ-SCHEDULER"); 103 //设置存储在quartz上文中的Spring应用上下文key 104 schedulerFactoryBean.setApplicationContextSchedulerContextKey("applicationContext"); 105 //设置属性 106 Properties properties = new Properties(); 107 //设置调度器实例名 108 properties.setProperty("org.quartz.scheduler.instanceName", "SCHEDULER-INSTANCE"); 109 //设置调度器实例ID,在cluster中使用,AUTO标识自动生成 110 properties.setProperty("org.quartz.scheduler.instanceId", "AUTO"); 111 //禁用rmi配置 112 properties.setProperty("org.quartz.scheduler.rmi.export", "false"); 113 //禁用rmi配置 114 properties.setProperty("org.quartz.scheduler.rmi.proxy", "false"); 115 //quartz线程池实现类 116 properties.setProperty("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool"); 117 //quartz线程池线程数 118 properties.setProperty("org.quartz.threadPool.threadCount", "10"); 119 //quartz线程池线程优先级 120 properties.setProperty("org.quartz.threadPool.threadPriority", "5"); 121 //quartz线程池是否自动加载数据库内的定时任务 122 properties.setProperty("org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread", "true"); 123 //Job错过执行时间的阈值 124 properties.setProperty("org.quartz.jobStore.misfireThreshold", "60000"); 125 //Job持久化方式配置 126 properties.setProperty("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX"); 127 //Job的JDBC持久化驱动,此处配置为MySql 128 properties.setProperty("org.quartz.jobStore.driverDelegateClass", "org.quartz.impl.jdbcjobstore.StdJDBCDelegate"); 129 //配置是否使用 130 properties.setProperty("org.quartz.jobStore.useProperties", "false"); 131 //持久化的quartz表结构前缀 132 properties.setProperty("org.quartz.jobStore.tablePrefix", "QRTZ_"); 133 //是否是集群quartz 134 properties.setProperty("org.quartz.jobStore.isClustered", "true"); 135 //集群quartz中节点有效性检查时间间隔 136 properties.setProperty("org.quartz.jobStore.clusterCheckinInterval", "20000"); 137 //错过执行时间的Job最大持有数 138 properties.setProperty("org.quartz.jobStore.maxMisfiresToHandleAtATime", "1"); 139 schedulerFactoryBean.setQuartzProperties(properties); 140 //返回结果 141 return schedulerFactoryBean; 142 } 143 144 }
1 /** 2 * 抽象定时任务,完成向quartz注册的功能 3 * Created by chenjunyi on 2018/6/6. 4 */ 5 @Slf4j 6 public abstract class AbstractScheduler implements InterruptableJob { 7 8 @Autowired 9 private Scheduler scheduler; 10 11 /** 12 * 向定时任务调度器注册 13 * @throws SchedulerException 注册时发生异常 14 */ 15 @PostConstruct 16 protected void register() throws SchedulerException { 17 //任务和触发器名称(若不进行设置,则quartz默认使用UUID,因此每次启动应用都会注册一个新任务) 18 String jobName = this.getClass().getSimpleName() + "Job"; 19 String triggerName = this.getClass().getSimpleName() + "Trigger"; 20 //设置定时任务 21 JobDetail jobDetail = JobBuilder.newJob(this.getClass()).withIdentity(jobName).build(); 22 //创建任务触发器 23 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(getCron()); 24 Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerName).withSchedule(scheduleBuilder).build(); 25 //将触发器与任务绑定到调度器内 26 Set<Trigger> triggers = new HashSet<>(); 27 triggers.add(trigger); 28 scheduler.scheduleJob(jobDetail, triggers, true); 29 log.info(">>>>>注册[Trigger={}, Job={}]的定时任务成功", triggerName, jobName); 30 } 31 32 /** 33 * 获取cron表达式 34 * @return cron表达式 35 */ 36 protected abstract String getCron(); 37 38 }
实现一个自定义的demo定时任务,并通过@Service交于Spring-IOC容器进行托管,代码如下:
1 /** 2 * 示例定时任务 3 * Created by chenjunyi on 2018/6/5. 4 */ 5 @Service 6 @PersistJobDataAfterExecution 7 @DisallowConcurrentExecution 8 public class DemoScheduler extends AbstractScheduler { 9 10 @Value("${env.cron.demoScheduler}") 11 private String cron; 12 13 @Autowired 14 private DemoService demoService; 15 16 @Override 17 public void interrupt() throws UnableToInterruptJobException { 18 19 } 20 21 @Override 22 public void execute(JobExecutionContext context) throws JobExecutionException { 23 demoService.sayHello(); 24 } 25 26 @Override 27 protected String getCron() { 28 return this.cron; 29 } 30 31 }
1 @Override 2 public Job newJob(TriggerFiredBundle bundle, Scheduler scheduler) throws SchedulerException { 3 try { 4 Object jobObject = createJobInstance(bundle); //直接根据class.newInstance获取实例 5 return adaptJob(jobObject); //job适配,判断job类型并进行包装,此处忽略 6 } catch (Exception ex) { 7 throw new SchedulerException("Job instantiation failed", ex); 8 } 9 } 10 11 protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { 12 return bundle.getJobDetail().getJobClass().newInstance(); 13 }
1 //参考博客链接:https://www.jianshu.com/p/d52d62fb2ac6;作者:恒宇少年 2 public static class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware { 3 4 /** spring-beanfactory */ 5 private transient AutowireCapableBeanFactory beanFactory; 6 7 @Override 8 public void setApplicationContext(final ApplicationContext context) { 9 beanFactory = context.getAutowireCapableBeanFactory(); 10 } 11 12 @Override 13 protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception { 14 final Object job = super.createJobInstance(bundle); 15 beanFactory.autowireBean(job); //通过newInstance获取job实例后,将其交付给spring-ioc 16 return job; 17 } 18 }
1 Class<? extends Job> clazz = bundle.getJobDetail().getJobClass(); 2 Job job = applicationContext.getBean(clazz);
标签:sso 返回结果 运行 org 框架 fir 抛出异常 定时 stat
原文地址:https://www.cnblogs.com/manayi/p/9152546.html