博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
003-spring结合java类调用quartz
阅读量:6074 次
发布时间:2019-06-20

本文共 7089 字,大约阅读时间需要 23 分钟。

一、利弊

  针对001 中设置,不方便程序中动态添加任务,只能使用配置进行配置任务,

    适用于已知固定时刻需要执行的任务。

  针对002中设置,不方便结合调用spring注入的实体

    使用于程序内部新增添的任务

二、结合spring以及动态添加任务

  1.编写ApplicationContext对象注入类

public class SpringContextUtil implements ApplicationContextAware {    private static ApplicationContext applicationContext;    @Override    public void setApplicationContext(ApplicationContext context)            throws BeansException {        SpringContextUtil.applicationContext = context;    }    public static Object getBean(String name){        return applicationContext.getBean(name);    }}

  2.spring,xml配置

  3.编写Job接口工厂

public class JobFactory extends AdaptableJobFactory {    @Autowired    private AutowireCapableBeanFactory capableBeanFactory;    @Override    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {        //调用父类的方法        Object jobInstance = super.createJobInstance(bundle);        //进行注入        capableBeanFactory.autowireBean(jobInstance);        return jobInstance;    }}

  4.注入Job工厂,以及quartz调度工厂

  5.java帮助类

public class TaskJobUtil {    private static final Logger logger = LoggerFactory.getLogger(TaskJobUtil.class);    private TaskJobUtil() {    }    /**     * 添加任务     *     * @param job            要调用的job类     * @param jobName        job名称     * @param cronExpression 任务触发时间表达式     * @param param          需要用到的参数,可在job类中的context获得     */    public static void addJob(Job job, String jobName, String cronExpression, Map param) {        Scheduler scheduler = null;        try {            removeJob(jobName, job.getClass().getCanonicalName() + "Group");//删除原任务            scheduler= (StdScheduler)SpringContextUtil.getBean("schedulerFactoryBean");            JobDetail jobDetail = getJobDetail(job, jobName, param);            String jobGroup = jobDetail.getGroup();            CronTrigger cronTrigger = getCronTrigger(job, jobName, jobGroup, cronExpression);            scheduler.scheduleJob(jobDetail, cronTrigger);            logger.info("添加任务:" + jobName);            startScheduler();        } catch (SchedulerException e) {            logger.error("", e);        }    }    /**     * 对外停止任务调度器方法     */    public static void stopJob() {        shutdownScheduler();    }    /**     * 启动调度器     */    protected static void startScheduler() {        Scheduler scheduler = null;        try {            scheduler= (StdScheduler)SpringContextUtil.getBean("schedulerFactoryBean");            //如果调度器未启动,启动调度器            if (scheduler != null && !scheduler.isStarted()) {                scheduler.start();            }        } catch (SchedulerException e) {            logger.error("", e);        }    }    /**     * 关闭调度器,关闭后任务也都清除     */    protected static void shutdownScheduler() {        Scheduler scheduler = null;        try {            scheduler= (StdScheduler)SpringContextUtil.getBean("schedulerFactoryBean");            //如果调度器未关闭,关闭调度器            if (scheduler != null && !scheduler.isShutdown()) {                scheduler.shutdown();            }        } catch (SchedulerException e) {            logger.error("", e);        }    }    /**     * 获取JobDetail     *     * @param job     * @param param     * @return     */    protected static JobDetail getJobDetail(Job job, String jobName, Map param) {        Class jobClazz = job.getClass();        if (jobName == null || "".equals(jobName)) {            jobName = jobClazz.getCanonicalName();        }        String jobGroup = jobClazz.getCanonicalName() + "Group";        JobDetail jobDetail = new JobDetail();        jobDetail.setDurability(true);        jobDetail.setRequestsRecovery(true);        jobDetail.setName(jobName);        jobDetail.setGroup(jobGroup);        jobDetail.setJobClass(jobClazz);        if (param != null && param.size() > 0) {            JobDataMap jobDataMap = new JobDataMap(param);//存放参数            jobDetail.setJobDataMap(jobDataMap);            logger.info("任务 " + jobName + " jobDetail存放的参数:" + param);        }        return jobDetail;    }    /**     * 获取触发器     *     * @param job     * @param jobName     * @param cronExpression     * @return     */    protected static CronTrigger getCronTrigger(Job job, String jobName, String jobGroup, String cronExpression) {        Class jobClazz = job.getClass();        String triggerName = jobName+jobClazz.getCanonicalName() + "Trigger";        String triggerGroup = jobClazz.getCanonicalName() + "TriggerGroup";        CronTrigger cronTrigger = new CronTrigger();        cronTrigger.setName(triggerName);        cronTrigger.setGroup(triggerGroup);        cronTrigger.setJobName(jobName);        cronTrigger.setJobGroup(jobGroup);        try {            cronTrigger.setCronExpression(cronExpression);//触发任务的时间表达式        } catch (Exception e) {            logger.error("",e);        }        logger.info("任务 " + jobName + " 触发时间:" + cronExpression);        return cronTrigger;    }    /**     * 删除job     *     * @param jobName     * @param jobGroup     */    public static void removeJob(String jobName, String jobGroup) {        logger.info("删除任务:jobName:" + jobName + " jobGroup:" + jobGroup);        Scheduler scheduler = null;        String[] jobNames = null;        try {            scheduler= (StdScheduler)SpringContextUtil.getBean("schedulerFactoryBean");            jobNames = scheduler.getJobNames(jobGroup);            if (jobNames == null || jobNames.length == 0) {                return;            }            for (String name : jobNames) {                if (name.equals(jobName)) {                    scheduler.pauseTrigger(jobName, jobGroup);//停止触发器                    scheduler.pauseJob(jobName, jobGroup);//暂停job                    scheduler.unscheduleJob(jobName, jobGroup);//取消预订的job                    scheduler.deleteJob(jobName, jobGroup);//删除job                }            }        } catch (SchedulerException e) {            logger.error("", e);        }    }    /**     * 获取任务列表     *     * @return     */    public static Map
> getJobList() { Scheduler scheduler = null; Map
> map = null; try { scheduler= (StdScheduler)SpringContextUtil.getBean("schedulerFactoryBean"); String[] jobGroupNames = scheduler.getJobGroupNames(); if (jobGroupNames == null || jobGroupNames.length == 0) { return null; } map = new HashMap
>(); for (String jobGroup : jobGroupNames) { String[] jobNames = scheduler.getJobNames(jobGroup); if (jobNames == null || jobNames.length == 0) { continue; } List
jobNameList = new ArrayList
(); for (String jobName : jobNames) { jobNameList.add(jobName); } map.put(jobGroup, jobNameList); } } catch (SchedulerException e) { logger.error("", e); } logger.info("获取job列表:" + map); return map; }}

  6.程序中使用

直接抵用

addJob等即可

 

转载地址:http://sxngx.baihongyu.com/

你可能感兴趣的文章
金融互联网之网络征信技术接口
查看>>
window mysql5.5错误
查看>>
华三----AP二层简单注册上线
查看>>
Linux 系统添加操作记录--命令审计功能
查看>>
运输层
查看>>
学习树莓派的第二天
查看>>
阿里云发布企业数字化及上云外包平台服务:阿里云众包平台
查看>>
Oracle审计参数
查看>>
Mysql-MMM高可用群集部署
查看>>
为什么分布式一定要有消息队列?
查看>>
高并发大容量NoSQL解决方案探索
查看>>
MySQL基础语句
查看>>
python操作sql server2008 pyodbc
查看>>
H3C AP胖转瘦方法大全
查看>>
基于tcp/ip以太网通信实现0-5v,4-20ma模拟量AI采集以及模拟量AO输出控制-综科智控...
查看>>
PHP执行系统命令的有几个常用的函数
查看>>
lnmp命令整理
查看>>
SparkStreaming基础理论
查看>>
程序员笔记|Sharding-JDBC 使用入门和基本配置
查看>>
关于安装H3c Cloud Lab的一些报错问题
查看>>