Spring 3整合Quartz 2实现动态定时任务

时间:2021-12-08 07:52:29

废话不说了直接上代码

  1. <bean id="schedulerFactoryBean"  
  2.         class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
  3.     <!--     <property name="startupDelay" value="180"/>  启动服务器后延迟启动定时任务-->  
  4. </bean>  
  5. <!--加载可执行的任务-->

    <bean id="springUtils" class="com.ais.plugin.quartz.job.task.SpringUtils" />

  6. public class ScheduleJob {


    public static final String STATUS_RUNNING = "1";
    public static final String STATUS_NOT_RUNNING = "0";
    public static final String CONCURRENT_IS = "1";
    public static final String CONCURRENT_NOT = "0";
    private String jobId;


    private Date createTime;


    private Date updateTime;
    /**
    * 任务名称
    */
    private String jobName;
    /**
    * 任务分组
    */
    private String jobGroup;
    /**
    * 任务状态 是否启动任务
    */
    private String jobStatus;
    /**
    * cron表达式
    */
    private String cronExpression;
    /**
    * 描述
    */
    private String description;
    /**
    * 任务执行时调用哪个类的方法 包名+类名
    */
    private String beanClass;
    /**
    * 任务是否有状态
    */
    private String isConcurrent;
    /**
    * spring bean
    */
    private String springId;
    /**
    * 任务调用的方法名
    */
    private String methodName;


    public String getJobId() {
    return jobId;
    }


    public void setJobId(String jobId) {
    this.jobId = jobId;
    }


    public Date getCreateTime() {
    return createTime;
    }


    public void setCreateTime(Date createTime) {
    this.createTime = createTime;
    }


    public Date getUpdateTime() {
    return updateTime;
    }


    public void setUpdateTime(Date updateTime) {
    this.updateTime = updateTime;
    }


    public String getJobName() {
    return jobName;
    }


    public void setJobName(String jobName) {
    this.jobName = jobName;
    }


    public String getJobGroup() {
    return jobGroup;
    }


    public void setJobGroup(String jobGroup) {
    this.jobGroup = jobGroup;
    }


    public String getJobStatus() {
    return jobStatus;
    }


    public void setJobStatus(String jobStatus) {
    this.jobStatus = jobStatus;
    }


    public String getCronExpression() {
    return cronExpression;
    }


    public void setCronExpression(String cronExpression) {
    this.cronExpression = cronExpression;
    }


    public String getDescription() {
    return description;
    }


    public void setDescription(String description) {
    this.description = description;
    }


    public String getBeanClass() {
    return beanClass;
    }


    public void setBeanClass(String beanClass) {
    this.beanClass = beanClass;
    }


    public String getIsConcurrent() {
    return isConcurrent;
    }


    public void setIsConcurrent(String isConcurrent) {
    this.isConcurrent = isConcurrent;
    }


    public String getSpringId() {
    return springId;
    }


    public void setSpringId(String springId) {
    this.springId = springId;
    }


    public String getMethodName() {
    return methodName;
    }


    public void setMethodName(String methodName) {
    this.methodName = methodName;
    }
    }

  7. public static String JOB_NAME = "动态任务调度";  
    public static String JOB_GROUP_NAME = "XLXXCC_JOB_GROUP";
                                                                    public void testTask() {  
    try {
    ScheduleJob job=new ScheduleJob();
    job.setJobId("9876");
    job.setJobName(JOB_NAME);
    job.setJobGroup(JOB_GROUP_NAME);
    job.setIsConcurrent(job.CONCURRENT_IS);
    job.setJobStatus("1");
    job.setCronExpression("0/5 * * * * ?");
    job.setBeanClass("com.ais.plugin.quartz.job.task.JobTaskService");
    job.setMethodName("testTask");
    jobTaskService.addJob(job);
    } catch (SchedulerException e) {
    e.printStackTrace();
    };
    }
  8. @Service("plugin.quartz.job.task.jobTaskService")
    public class JobTaskService {
    public final Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;
    //private Scheduler scheduler;


    /**
    * 添加任务

    * @param scheduleJob
    * @throws SchedulerException
    */
    public void addJob(ScheduleJob job) throws SchedulerException {
    if (job == null || !ScheduleJob.STATUS_RUNNING.equals(job.getJobStatus())) {
    return;
    }
    Scheduler scheduler = schedulerFactoryBean.getScheduler();
    log.debug(scheduler + ".......................................................................................add");
    TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());


    CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);


    // 不存在,创建一个
    if (null == trigger) {
    //Class clazz = ScheduleJob.CONCURRENT_IS.equals(job.getIsConcurrent()) ? QuartzJobFactory.class : QuartzJobFactoryDisallowConcurrentExecution.class;


    JobDetail jobDetail = JobBuilder.newJob(QuartzJobFactory.class).withIdentity(job.getJobName(), job.getJobGroup()).build();


    jobDetail.getJobDataMap().put("scheduleJob", job);


    CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());


    trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(), job.getJobGroup()).withSchedule(scheduleBuilder).build();


    scheduler.scheduleJob(jobDetail, trigger);
    } else {
    // Trigger已存在,那么更新相应的定时设置
    CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());


    // 按新的cronExpression表达式重新构建trigger
    trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();


    // 按新的trigger重新设置job执行
    scheduler.rescheduleJob(triggerKey, trigger);
    }
    }

    public void testTask(){
    System.out.println("====testTask======");
    }


    }
  9. public final class SpringUtils implements BeanFactoryPostProcessor {


    private static ConfigurableListableBeanFactory beanFactory; // Spring应用上下文环境


    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    SpringUtils.beanFactory = beanFactory;
    }


    /**
    * 获取对象

    * @param name
    * @return Object 一个以所给名字注册的bean的实例
    * @throws org.springframework.beans.BeansException

    */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
    return (T) beanFactory.getBean(name);
    }


    /**
    * 获取类型为requiredType的对象

    * @param clz
    * @return
    * @throws org.springframework.beans.BeansException

    */
    public static <T> T getBean(Class<T> clz) throws BeansException {
    T result = (T) beanFactory.getBean(clz);
    return result;
    }


    /**
    * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true

    * @param name
    * @return boolean
    */
    public static boolean containsBean(String name) {
    return beanFactory.containsBean(name);
    }


    /**
    * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。
    * 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)

    * @param name
    * @return boolean
    * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException

    */
    public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
    return beanFactory.isSingleton(name);
    }


    /**
    * @param name
    * @return Class 注册对象的类型
    * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException

    */
    public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
    return beanFactory.getType(name);
    }


    /**
    * 如果给定的bean名字在bean定义中有别名,则返回这些别名

    * @param name
    * @return
    * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException

    */
    public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
    return beanFactory.getAliases(name);
    }


    }
  10. public class TaskUtils {
    public final static Logger log = Logger.getLogger(TaskUtils.class);


    /**
    * 通过反射调用scheduleJob中定义的方法

    * @param scheduleJob
    */
    public static void invokMethod(ScheduleJob scheduleJob) {
    Object object = null;
    Class clazz = null;
    if (StringUtils.isNotBlank(scheduleJob.getSpringId())) {
    object = SpringUtils.getBean(scheduleJob.getSpringId());
    } else if (StringUtils.isNotBlank(scheduleJob.getBeanClass())) {
    try {
    clazz = Class.forName(scheduleJob.getBeanClass());
    object = clazz.newInstance();
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }


    }
    if (object == null) {
    log.error("任务名称 = [" + scheduleJob.getJobName() + "]---------------未启动成功,请检查是否配置正确!!!");
    return;
    }
    clazz = object.getClass();
    Method method = null;
    try {
    method = clazz.getDeclaredMethod(scheduleJob.getMethodName());
    } catch (NoSuchMethodException e) {
    log.error("任务名称 = [" + scheduleJob.getJobName() + "]---------------未启动成功,方法名设置错误!!!");
    } catch (SecurityException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    if (method != null) {
    try {
    method.invoke(object);
    } catch (IllegalAccessException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IllegalArgumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (InvocationTargetException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    System.out.println("任务名称 = [" + scheduleJob.getJobName() + "]----------启动成功");
    }
    }
  11. Spring 3整合Quartz 2实现动态定时任务
  12. 在网上看一些例子都没有运行成功,这是我简单写的例子请大家多多指教,写的不好勿喷,其中借鉴有网上的代码