spring+quartz任务动态调度

//xml配置quartz容器组件
<beans>
    //将job注入spring容器,可以在任务执行类中获取spring容器的bean对象,执行业务操作
    <bean id="jobFactory" class="cn.whcds.data.schedule.JobFactory"></bean>
    <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="jobFactory" ref="jobFactory"></property>
    </bean>
    //系统初始时,将数据库中的任务加载,传入scheduler组件,确保初始化类中操作的是同一scheduler对象
    <bean id="scheduleInit" class="cn.whcds.data.util.ScheduleInit">
        <property name="scheduler" ref="scheduler"></property>
    </bean>
</beans>
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;

public class JobFactory extends AdaptableJobFactory {
    //这个对象Spring会帮我们自动注入进来,也属于Spring技术范畴.
    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;
    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        //调用父类的方法
        Object jobInstance = super.createJobInstance(bundle);
        //进行注入,这属于Spring的技术,不清楚的可以查看Spring的API.
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
}
//系统初始化加载数据库的job

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.impl.JobDetailImpl;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;


public class ScheduleInit implements InitializingBean {

    private Scheduler scheduler;
    public Scheduler getScheduler() {
        return scheduler;
    }
    public void setScheduler(Scheduler scheduler) {
        this.scheduler = scheduler;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("初始化任务调度!");
        //业务代码
/**

**/
        System.out.println("初始化任务调度完毕!");
    }
}
//任务执行类

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class QuartzJob extends QuartzJobBean  {
    @Resource
    //注入业务层bean
    private final static QuartzManager quartzManager = new QuartzManager();
    @Override
    public void executeInternal(JobExecutionContext context) throws JobExecutionException {
    }
}
//任务调度管理工具类,通过此类进行任务的调度:执行,修改,删除

import org.quartz.*;
import org.quartz.impl.JobDetailImpl;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.web.context.ContextLoader;
public class QuartzManager {
    private static Scheduler scheduler = (Scheduler) ContextLoader.getCurrentWebApplicationContext().getBean("scheduler");

//    private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();

    private static String JOB_GROUP_NAME = "EXTJWEB_JOBGROUP_NAME";
    private static String TRIGGER_GROUP_NAME = "EXTJWEB_TRIGGERGROUP_NAME";


    /**
     * @Description: 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名
     *
     * @param jobName
     *            任务名
     * @param cls
     *            任务
     * @param time
     *            时间设置,参考quartz说明文档
     *
     * 业务实现时,将jobname换成id,保证key的唯一性
     */
    public static void addJob(String jobName, Class cls, String time) {
        try {
//            Scheduler scheduler = gSchedulerFactory.getScheduler();
            boolean isShutdown = scheduler.isShutdown();
            if(isShutdown){
                scheduler.start();
            }
            JobDetail jobDetail = new JobDetailImpl(jobName, JOB_GROUP_NAME, cls);// 任务名,任务组,任务执行类
            CronTrigger trigger = new CronTriggerImpl(jobName, TRIGGER_GROUP_NAME,time);// 触发器名,触发器组
            scheduler.scheduleJob(jobDetail, trigger);
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description: 添加一个定时任务
     *
     * @param jobName
     *            任务名
     * @param jobGroupName
     *            任务组名
     * @param triggerName
     *            触发器名
     * @param triggerGroupName
     *            触发器组名
     * @param jobClass
     *            任务
     * @param time
     *            时间设置,参考quartz说明文档
     *
     */
    public static void addJob(String jobName, String jobGroupName,
                              String triggerName, String triggerGroupName, Class jobClass,
                              String time) {
        try {
//            Scheduler sched = gSchedulerFactory.getScheduler();
            JobDetail jobDetail = new JobDetailImpl(jobName, jobGroupName, jobClass);// 任务名,任务组,任务执行类
            // 触发器
            CronTrigger trigger = new CronTriggerImpl(triggerName, triggerGroupName,time);// 触发器名,触发器组
//            trigger.setCronExpression(time);// 触发器时间设定
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description: 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名)
     *
     * @param jobName
     * @param time
     *
     */
    public static void modifyJobTime(String jobName, String time) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName,TRIGGER_GROUP_NAME);
            JobKey jobKey = new JobKey(jobName,JOB_GROUP_NAME);

//            Scheduler sched = gSchedulerFactory.getScheduler();
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            if (trigger == null) {
                return;
            }
            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(time)) {
                JobDetail jobDetail = scheduler.getJobDetail(jobKey);
                Class objJobClass = jobDetail.getJobClass();
                removeJob(jobName);
                addJob(jobName, objJobClass, time);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description: 修改一个任务的触发时间
     *
     * @param triggerName
     * @param triggerGroupName
     * @param time
     *
     */
    public static void modifyJobTime(String triggerName,
                                     String triggerGroupName, String time) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName,TRIGGER_GROUP_NAME);
            JobKey jobKey = new JobKey(triggerName,JOB_GROUP_NAME);

//            Scheduler sched = gSchedulerFactory.getScheduler();
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            if (trigger == null) {
                return;
            }
            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(time)) {
                CronTriggerImpl ct =  (CronTriggerImpl)trigger;
                // 修改时间
                ct.setCronExpression(time);
                // 重启触发器
                scheduler.resumeTrigger(triggerKey);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description: 移除一个任务(使用默认的任务组名,触发器名,触发器组名)
     *
     * @param jobName
     *
     */
    public static void removeJob(String jobName) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName,TRIGGER_GROUP_NAME);
            JobKey jobKey = new JobKey(jobName,JOB_GROUP_NAME);

//            Scheduler sched = gSchedulerFactory.getScheduler();
            scheduler.pauseTrigger(triggerKey);// 停止触发器
            scheduler.unscheduleJob(triggerKey);// 移除触发器
            scheduler.deleteJob(jobKey);// 删除任务
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description: 移除一个任务
     *
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param triggerGroupName
     *
     */
    public static void removeJob(String jobName, String jobGroupName,
                                 String triggerName, String triggerGroupName) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName,jobGroupName);
            JobKey jobKey = new JobKey(triggerName,triggerGroupName);

//            Scheduler sched = gSchedulerFactory.getScheduler();
            scheduler.pauseTrigger(triggerKey);// 停止触发器
            scheduler.unscheduleJob(triggerKey);// 移除触发器
            scheduler.deleteJob(jobKey);// 删除任务
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description:启动所有定时任务
     *
     *
     * @Title: QuartzManager.java
     * @Copyright: Copyright (c) 2014
     *
     */
    public static void startJobs() {
        try {
//            Scheduler sched = gSchedulerFactory.getScheduler();
            scheduler.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description:关闭所有定时任务
     *
     *
     * @Title: QuartzManager.java
     * @Copyright: Copyright (c) 2014
     *
     */
    public static void shutdownJobs() {
        try {
//            Scheduler sched = gSchedulerFactory.getScheduler();
            if (!scheduler.isShutdown()) {
                scheduler.shutdown();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

 

上一篇:Fiddler下载安装以及配置教程~~实现手机抓包


下一篇:golang冒泡、选择、插入、快速排序 思路和代码