相关技术

本文采用spring + quartz的方案。使用mysql作为任务的持久化,支持分布式。

自定义注解

1.启用定时任务

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(QuartzConfig.class) //引入配置
@Documented
public @interface EnableMScheduling { } //该注解需要放在application启动类上,标识启用定时任务,它的作用就是配置、解析任务以及启动调

2.标识调度类

@Target(value = ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Component
public @interface MScheduleClass { /**
* 任务分组,页面显示作用
* @return
*/
String module() default "系统"; /**
* 描述,提示作用
* @return
*/
String desc() default ""; }
//该注解放置在类上,标识指定的类是一组定时任务,其中需要设置任务分组,描述

3.标识执行的方法

@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MSchedule { /**
* 任务名称
* @return
*/
String title() default ""; /**
* 调度触发的corn表达式 : 用作Job的触发器,目前只支持一个触发器表达式。
*/
String corn(); /**
* 描述
*/
String desc() default ""; /**
* 参数
*/
String param() default "";
}
//该注解标识在@MScheduleClass标识的类中的方法中,标识指定的方式是任务执行的方法。

配置类

import javax.sql.DataSource;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager; public class QuartzConfig { /**
* 配置任务调度器
* 使用项目数据源作为quartz数据源
* @param jobFactory 自定义配置任务工厂
* @param dataSource 数据源实例
* @return
* @throws Exception
*/
@Bean(destroyMethod = "destroy")
public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource,
ObjectProvider<PlatformTransactionManager> transactionManager) throws Exception { SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
// 项目启动完成后,等待10秒后开始执行调度器初始化
//schedulerFactoryBean.setStartupDelay(10);
// 设置调度器自动运行
schedulerFactoryBean.setAutoStartup(false);
// 设置数据源,使用与项目统一数据源
schedulerFactoryBean.setDataSource(dataSource); PlatformTransactionManager txManager = transactionManager.getIfUnique();
if (txManager != null) {
schedulerFactoryBean.setTransactionManager(txManager);
}
// 设置上下文spring bean name
schedulerFactoryBean.setApplicationContextSchedulerContextKey("applicationContext");
// 设置配置文件位置
schedulerFactoryBean.setConfigLocation(new ClassPathResource("/quartz.properties"));
return schedulerFactoryBean;
} @Bean
public MScheduleBeanPostProcessor mScheduleBeanPostProcessor() {
return new MScheduleBeanPostProcessor();
}
}

其中dataSource我自己用的阿里的druid。  具体配置自行处理

quartz.properites

#调度器实例名称
org.quartz.scheduler.instanceName = quartzScheduler #调度器实例编号自动生成
org.quartz.scheduler.instanceId = AUTO #持久化方式配置
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX #持久化方式配置数据驱动,MySQL数据库
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate #quartz相关数据表前缀名
org.quartz.jobStore.tablePrefix = QRTZ_ #开启分布式部署
org.quartz.jobStore.isClustered = true
#配置是否使用
org.quartz.jobStore.useProperties = false #分布式节点有效性检查时间间隔,单位:毫秒
org.quartz.jobStore.clusterCheckinInterval = 20000 #线程池实现类
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool #执行最大并发线程数量
org.quartz.threadPool.threadCount = 10 #线程优先级
org.quartz.threadPool.threadPriority = 5 #配置是否启动自动加载数据库内的定时任务,默认true
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true

quartz初始化的数据库表在org/quartz/impl/jdbcjobstore/tables_@@platform@@.sql

注解解析beanPosrProcessor

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set; import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent; import com.mustr.cluster.annotation.MSchedule;
import com.mustr.cluster.annotation.MScheduleClass; import lombok.extern.slf4j.Slf4j; @Slf4j
public class MScheduleBeanPostProcessor implements BeanPostProcessor, ApplicationListener<ContextRefreshedEvent>, DisposableBean { @Autowired
private Scheduler scheduler; private List<MustrTask> tasks = new ArrayList<>(); @Override
public void destroy() throws Exception {
scheduler.shutdown();
} @Override
public void onApplicationEvent(ContextRefreshedEvent event) {
log.info("all scheduler tasks total {}", tasks.size()); try {
//先把原来的都删除
Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.anyGroup());
scheduler.deleteJobs(new ArrayList<>(jobKeys));
} catch (SchedulerException e1) {
e1.printStackTrace();
} //重新添加新的
tasks.forEach(task -> {
try {
scheduler.scheduleJob(task.getJobDetail(), task.getTrigger());
} catch (SchedulerException e) {
e.printStackTrace();
}
}); try {
scheduler.start(); //启动调度器
} catch (SchedulerException e) {
e.printStackTrace();
}
} @Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
MScheduleClass msClass = bean.getClass().getAnnotation(MScheduleClass.class);
if (msClass == null) {
return bean;
} String group = bean.getClass().getSimpleName();
Method[] methods = bean.getClass().getDeclaredMethods();
if (methods == null) {
return bean;
} for (Method method : methods) {
MSchedule mSchedule = method.getAnnotation(MSchedule.class);
if (mSchedule == null) {
continue;
}
hanlderSchedule(group, mSchedule, method, bean);
} return bean;
} private void hanlderSchedule(String group, MSchedule mSchedule, Method method, Object bean) {
String jobName = method.getName(); JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("targetClass", bean);
jobDataMap.put("targetMethod", method.getName());
jobDataMap.put("arguments", mSchedule.param()); JobDetail jobDetail = JobBuilder.newJob(MustrCommonJob.class)
.setJobData(jobDataMap)
.withIdentity(new JobKey(jobName, group))
.withDescription(mSchedule.desc())
.storeDurably()
.build(); Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity(new TriggerKey(jobName, group))
.withDescription(mSchedule.desc())
.withSchedule(CronScheduleBuilder.cronSchedule(mSchedule.corn()).withMisfireHandlingInstructionDoNothing())
.forJob(jobDetail)
.build(); tasks.add(new MustrTask(jobDetail, trigger));
}
}

该类就是解析自定义注解的@MScheduleClass和@MSchedule标识的任务。封装jobDetail和Trigger。

任务job统一使用MustrCommonJob通过反射来执行配置的指定类的指定方法

 

MustrTask

import org.quartz.JobDetail;
import org.quartz.Trigger; import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter; @Setter
@Getter
@AllArgsConstructor
public class MustrTask { private JobDetail jobDetail;
private Trigger trigger;
}

任务类

import java.io.Serializable;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.util.MethodInvoker; public class MustrCommonJob implements Job, Serializable{
private static final long serialVersionUID = 8651275978441122356L; @Override
public void execute(JobExecutionContext context) throws JobExecutionException {
Object targetClass = context.getMergedJobDataMap().get("targetClass");
String targetMethod = context.getMergedJobDataMap().getString("targetMethod");
String param = context.getMergedJobDataMap().getString("arguments"); //前置处理
// do .... try {
MethodInvoker methodInvoker = new MethodInvoker();
methodInvoker.setTargetObject(targetClass);
methodInvoker.setTargetMethod(targetMethod);
if (param != null && !"".equals(param)) {
String[] params = param.split(",");
Object[] temp = new Object[params.length];
for (int i = 0; i < params.length; i++) {
temp[i] = params[i];
}
methodInvoker.setArguments(temp);
}
methodInvoker.prepare();
methodInvoker.invoke();
} catch (Exception e) {
e.printStackTrace();
} finally { //后置处理
// do ... 如记录日志
}
} }
该类实现了quartz的job接口。通过反射调用指定的方法

一个简单的demo

import java.io.Serializable;
import java.time.LocalDateTime; import com.mustr.cluster.annotation.MSchedule;
import com.mustr.cluster.annotation.MScheduleClass; @MScheduleClass(module = "系统", desc = "测试组")
public class HelloSchedule implements Serializable{
private static final long serialVersionUID = 3619058186885794136L; /*@MSchedule(corn = "0/30 * * * * ?", desc = "打印hello world")
public void hello() {
System.out.println("hello mustr..... <<<:::>>>" + LocalDateTime.now());
}*/ @MSchedule(corn = "0/10 * * * * ?", desc = "打印hello world")
public void hello1() {
System.out.println("<<<<hello1 mustr..... <<<:::>>>" + LocalDateTime.now());
}
}

最后一步

在程序启动类中加入 @EnableMScheduling注解,启动项目即可看到控制台打印

本文代码:https://github.com/Mustr/mustr-quartz-boot

spring + quartz 分布式自定义注解的更多相关文章

  1. spring quartz分布式任务计划

    spring quartz分布式任务计划 环境: 通过maven管理的spring mvc工程,且已经成功连接数据库. 数据库表结构 /*Table structure for table `qrtz ...

  2. redis分布式锁-spring boot aop+自定义注解实现分布式锁

    接这这一篇redis分布式锁-java实现末尾,实现aop+自定义注解 实现分布式锁 1.为什么需要 声明式的分布式锁 编程式分布式锁每次实现都要单独实现,但业务量大功能复杂时,使用编程式分布式锁无疑 ...

  3. 使用spring aspect控制自定义注解

    自定义注解:这里是一个处理异常的注解,当调用方法发生异常时,返回异常信息 /** * ErrorCode: * * @author yangzhenlong * @since 2016/7/21 */ ...

  4. spring AOP 和自定义注解进行身份验证

    一个SSH的项目(springmvc+hibernate),需要提供接口给app使用.首先考虑的就是权限问题,app要遵循极简模式,部分内容无需验证,用过滤器不能解决某些无需验证的方法 所以最终选择用 ...

  5. Spring实现封装自定义注解@Trimmed清除字符串前后的空格

    在Spring中实现字符串清除的方法有很多,原生方法String自带trim()方法,或者使用StringUtils提供的trim...方法. 通常可以将上面的方式封装成自定义注解的形式去实现来节省更 ...

  6. Spring Boot中自定义注解+AOP实现主备库切换

    摘要: 本篇文章的场景是做调度中心和监控中心时的需求,后端使用TDDL实现分表分库,需求:实现关键业务的查询监控,当用Mybatis查询数据时需要从主库切换到备库或者直接连到备库上查询,从而减小主库的 ...

  7. Spring Boot实现自定义注解

    在Spring Boot项目中可以使用AOP实现自定义注解,从而实现统一.侵入性小的自定义功能. 实现自定义注解的过程也比较简单,只需要3步,下面实现一个统一打印日志的自定义注解: 1. 引入AOP依 ...

  8. spring boot通过自定义注解和AOP拦截指定的请求

    一 准备工作 1.1 添加依赖 通过spring boot创建好工程后,添加如下依赖,不然工程中无法使用切面的注解,就无法对制定的方法进行拦截 <dependency> <group ...

  9. spring mvc实现自定义注解

    实现方式:使用@Aspect实现: 1. 新建注解接口:CheckSign package com.soeasy.web.utils; import org.springframework.core. ...

随机推荐

  1. JDK 8 新增的 LongAdder,得过来看一下

    前言 在介绍 AtomicInteger 时,已经说明在高并发下大量线程去竞争更新同一个原子变量时,因为只有一个线程能够更新成功,其他的线程在竞争失败后,只能一直循环,不断的进行 CAS 尝试,从而浪 ...

  2. 面试 之 nginx,负载,动静分离

    大家先看这个逻辑图 为什么我们要这样去架构我们的一个项目呢? 这样做的话,动态请求要先访问 A,A 转发访问 B,再由 B 返回结果给 A,A 最后又将结果返回给客户端这样是不是很麻烦? 最初开发的时 ...

  3. c#导入文件

    string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Administrator\Desktop\2.txt",Encod ...

  4. MQ-gogogo

    1. RocketMQ https://github.com/alibaba/RocketMQ/wiki/quick-start 2. RabbitMQ https://www.rabbitmq.co ...

  5. 没有真实串口设备时使用"虚拟串口驱动"调试你的串口代码

    目录 前言 示例代码 总结 前言 很多时候需要编写串口代码,但是又没有真实串口设备来调试代码.以及本身就是要操作2个串口的情况,可以使用"虚拟串口驱动"工具方便的调试代码. 使用方 ...

  6. python菜鸟教程学习3:基础语法

    菜鸟教程对应网址:https://www.runoob.com/python3/python3-basic-syntax.html 编码:python3用UTF-8编码,所有字符串都是unicode字 ...

  7. haproxy 思考

    通过代理服务器在两个TCP接连之间转发数据是一个常见的需求,然后通常部署的时候涉及到(虚拟)服务器.真实服务器.防护设备.涉及到多个ip地址相关联,改动一个IP就需要修改配置. 比如反向服务器部署的时 ...

  8. C#高级编程之反射

    反射的定义 MSDN定义:反射提供描述程序集.模块和类型的对象(Type类型). 可以使用反射动态地创建类型的实例,将类型绑定到现有对象,或从现有对象中获取类型,然后调用其方法或访问器字段和属性. 如 ...

  9. 各种有趣vbs,bat脚本

    短信轰炸.vbs Dim btn,ie Set ie = WScript.CreateObject("InternetExplorer.Application") ie.Visib ...

  10. Android RFID调试总结

    调试了包括驱动,jni层,当然也熟悉了下应用层.    1. 驱动层包括修改:        device/eastaeon/aeon6735_65c_l/init.project.rc    //去 ...