- 鑑於對Spring實現的@Scheduled的調度和SchedulerFactoryBean的研究發現,基於Spring的調度封裝雖知足了大多需求,但其爲了簡化使用方式,過分封裝使得Job並不容易控制和運維,致使開發對Job的控制和運維成本上升;下面是本人基於Quartz和Spring及Annotation開發的單機版調度配置DEMO,知足單機調度的大部分需求和管理、運維操做並解放對配置文件的繁瑣操做;
下面對Spring的@Scheduled註解和SchedulerFactoryBean配置及自定義@SchedulerJob作對比;
功能點 | Spring @Scheduled | 自定義@SchedulerJob |
---|---|---|
可控制 | 否 | 是 |
可運維 | 否 | 是 |
可頁面化 | 否 | 是 |
可統一跟蹤業務狀態 | 否 | 是 |
可統一跟蹤調度狀態 | 否 | 是 |
支持cron表達式 | 是 | 是 |
支持相似ScheduledExecutorService的定時調度 | 是 | 否 |
/**
* @author baiyunpeng
* 抽取Job控制信息
*/
MethodInvokingJobDetailFactoryBean methodInvoker = (MethodInvokingJobDetailFactoryBean) jobDetail.getJobDataMap().get("methodInvoker");
String jobName = jobDetail.getKey().getName();
String group = jobDetail.getKey().getGroup();
String className = methodInvoker.getTargetClass().getName();
複製代碼
@Slf4j(topic = "dynamic-datasource")
@Component
public class DetectJob {
/**
* 做業配置 value=做業名,group=做業所屬組,init=true爲容器建立完畢時當即觸發
*/
@SchedulerJob(value = "detectDataSource",cron = "${cron.detect.data.source}",group = "dynamic-datasource",
descrption="動態數據源切換",init = true)
public void detectDataSource(){
log.info(VariableUtils.join(SystemConstants.Symbol.DELIMITER,"dynamic-datasource","detectDataSource"));
}
}
複製代碼
##cron表達式
cron.detect.data.source=1 * * * * ?
複製代碼
經過頁面可對做業進行統一的監控和管理(觸發、暫停、恢復、動態添加、參數下發)及報警等操做;bash
簡要列出如下功能點:併發
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SchedulerJob {
/**
* 做業名
* @return
*/
String value();
/**
* 表達式
* @return
*/
String cron();
/**
* 是否初始化時當即執行
* @return
*/
boolean init() default false;
/**
* 是否人爲控制
* @return
*/
boolean control() default false;
/**
* 所屬組
* @return
*/
String group() default "default";
/**
* 做業描述
* @return
*/
String descrption() default "";
/**
* 做業執行器
* @return
*/
Class jobClass() default SimpleJob.class;
}
@Target({ElementType.METHOD,ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface SchedulerJobs {
/**
* 註解集
* @return
*/
SchedulerJob[] value();
}
複製代碼
@Slf4j
@Configuration
public class SchedulerBean implements InitializingBean, DisposableBean {
private Scheduler scheduler;
@Value("#{schdulerProperties['quartz.thread.count']}")
private String threadCount;
@Override
public void destroy() throws Exception {
scheduler.shutdown();
}
@Override
public void afterPropertiesSet() throws Exception {
createScheduler();
}
/**
* 建立調度
* @throws SchedulerException
*/
public void createScheduler() throws SchedulerException {
StdSchedulerFactory factory = new StdSchedulerFactory();
factory.initialize(getBaseQuartzProperties());
this.scheduler = factory.getScheduler();
}
/**
* 做業配置
* @return
*/
private Properties getBaseQuartzProperties() {
Properties result = new Properties();
result.put("org.quartz.threadPool.class", org.quartz.simpl.SimpleThreadPool.class.getName());
result.put("org.quartz.threadPool.threadCount", threadCount);
result.put("org.quartz.scheduler.threadName", "baiyunpeng-scheduler");
result.put("org.quartz.scheduler.instanceName", "baiyunpeng-scheduler");
result.put("org.quartz.jobStore.misfireThreshold", "1");
return result;
}
/**
* 建立做業
* @param jobParam
* @throws SchedulerException
*/
public void createJob(JobParam jobParam) throws SchedulerException {
SchedulerJob schedulerJob = jobParam.getSchedulerJob();
JobDetail jobDetail = JobBuilder.newJob(schedulerJob.jobClass())
.withIdentity(jobParam.getJobKey())
.withDescription(jobParam.getJobKey().getName())
.build();
addJobDataMap(jobDetail,jobParam.getTarget(),jobParam.getTargetMethod());
this.scheduler.scheduleJob(jobDetail,createTrigger(jobParam.getJobKey(),jobParam.getCron()));
}
/**
* 建立觸發器
* @param jobKey
* @param cron
* @return
*/
private Trigger createTrigger(JobKey jobKey, String cron) {
return TriggerBuilder.newTrigger().withIdentity(jobKey.getName(),jobKey.getGroup())
.withSchedule(CronScheduleBuilder.cronSchedule(cron)
.withMisfireHandlingInstructionDoNothing()).build();
}
/**
* 添加做業map
* @param jobDetail
* @param target
* @param targetMethod
*/
private void addJobDataMap(JobDetail jobDetail, Object target, Method targetMethod) {
JobDataMap jobDataMap = jobDetail.getJobDataMap();
jobDataMap.put("executeJob",target);
jobDataMap.put("executeMethod",targetMethod);
}
public Scheduler getScheduler() {
return scheduler;
}
public void start() throws SchedulerException {
this.scheduler.start();
}
}
複製代碼
/**
* 做業抽象類
* @author baiyunpeng
*/
public abstract class ExecuteJob implements Job {
protected Object executeJob;
protected Method executeMethod;
protected void setExecuteJob(Object executeJob) {
this.executeJob = executeJob;
}
protected void setExecuteMethod(Method executeMethod) {
this.executeMethod = executeMethod;
}
}
/**
* 非併發執行
* @author baiyunpeng
*/
@Slf4j
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class SimpleJob extends ExecuteJob {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
try {
executeMethod.invoke(executeJob);
} catch (IllegalAccessException | InvocationTargetException e) {
log.error(VariableUtils.join(SystemConstants.Symbol.DELIMITER,this.getClass().getName(), ExceptionUtils.getRootCauseMessage(e)));
}
}
}
/**
* 可併發執行
* @author baiyunpeng
*/
@Slf4j
public class ConcurrentJob extends ExecuteJob{
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
try {
executeMethod.invoke(executeJob);
} catch (IllegalAccessException | InvocationTargetException e) {
log.error(VariableUtils.join(SystemConstants.Symbol.DELIMITER,this.getClass().getName(), ExceptionUtils.getRootCauseMessage(e)));
}
}
}
複製代碼
/**
* 做業配置解析
* @param scheduled
* @param method
* @param bean
*/
protected void processScheduled(SchedulerJob scheduled, Method method, Object bean) {
Method invocableMethod = AopUtils.selectInvocableMethod(method, bean.getClass());
String cron = scheduled.cron();
if(StringUtils.hasText(cron)){
if(Objects.nonNull(this.embeddedValueResolver)){
cron = this.embeddedValueResolver.resolveStringValue(cron);
}
jobParams.add(new JobParam(scheduled,bean,invocableMethod,new JobKey(scheduled.value(),scheduled.group()),cron));
}
}
/**
* 做業初始化
*/
private void finishRegister() {
if(Objects.isNull(this.schedulerBean)){
SchedulerBean schedulerBean = beanFactory.getBean(SCHEDULER_BEAN, SchedulerBean.class);
AssertUtil.assertNull(schedulerBean, SystemErrorCode.NS000000,"the scheduler bean init error");
this.schedulerBean = schedulerBean;
try {
jobParams.parallelStream().forEach(jobParam -> {
try {
this.schedulerBean.createJob(jobParam);
SchedulerJob schedulerJob = jobParam.getSchedulerJob();
if(!schedulerJob.control()){
if (schedulerJob.init()){
this.schedulerBean.getScheduler().triggerJob(jobParam.getJobKey());
}
}else {
this.schedulerBean.getScheduler().pauseJob(jobParam.getJobKey());
}
} catch (SchedulerException e) {
log.error(VariableUtils.join(SystemConstants.Symbol.DELIMITER,"the scheduler job init error", ExceptionUtils.getRootCauseMessage(e)));
System.exit(1);
}
});
schedulerBean.start();
}catch (Exception e){
log.error(VariableUtils.join(SystemConstants.Symbol.DELIMITER,"the scheduler job init error", ExceptionUtils.getRootCauseMessage(e)));
System.exit(1);
}
}
}
複製代碼