java中如何用Quartz框架来实现动态定时任务(二)

来源:互联网 发布:微信备案域名 编辑:程序博客网 时间:2024/05/19 04:53

题记:

之前做的项目中有五个平台,分别是出版平台、图书馆平台、发行平台、零售平台、中心平台。

出版平台:主要是录入图书信息和图书的相关图片和附件信息

图书馆平台:将出版发送过来的图书进行借阅和副本的录入

发布平台和零售平台:给图书录入订购、销售、库存的数量的信息

中心平台:跟前台页面进行交互(管理前台页面)

需求一:

在中心平台中,信息发布管理模块有4个管理,分别是:首页大图管理、行业信息管理、友情链接管理、文件发布管理,除了在原有的手动发布(后台点击发布,前台会展示后台所发布的信息)的基础上,实现定时发布效果(自己设置任意时间,系统会根据你设置的时间来进行发布)。

需求一页面效果:



需求二:

出版、图书馆、发行、零售这四个平台的信息是可以相互传递的,如出版可以发送给图书馆、发行和零售,其他几个也可以发送给任何一个平台(点对点发送),用的是消息队列(activemq)来实现了,也是这个项目的核心功能,这个也是,在原来手动发送的基础上,实现定时发送,这个要复杂一些,实现单独的模块,数据交换的策略管理,根据设置的要求和相应的时间,定时进行发送。

需求二页面效果:





说明:这里可以根据通告类型、出版状态、接收对象(是发送给哪个平台,可以任意选择)、发送日期和时间进行定时发送

-----------------------------------------------------------------------------------------------------------(人工分割线)

项目展示图:


说明:这里我单独定义一个包,来写定时任务的代码

ScheduleJobController:(这里控制层没有在这写,因为,我要在具体的发送的controller来写,这里定义了出来,但是没有用到):

package com.jetsen.quartz.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;/** * @author LY * @date 2016-07-25 *///暂时用不到,定时分布在各个需要的模块中@RequestMapping("schedule")@Controllerpublic class ScheduleJobController {}
ScheduleJob:

package com.jetsen.quartz.entity;import java.util.Date;import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.ManyToOne;import javax.persistence.Table;import org.hibernate.annotations.Cache;import org.hibernate.annotations.CacheConcurrencyStrategy;import com.jetsen.model.book.Strategy;/** * @author LY * @date 2016-07-25 */@Entity@Table(name = "task_scheduleJob")public class ScheduleJob{    /** 任务id */private Long   scheduleJobId;    /** 任务名称 */    private String  jobName;    /** 任务别名 */    private String  aliasName;    /** 任务分组 */    private String  jobGroup;    /** 触发器 */    private String  jobTrigger;    /** 任务状态 */    private String    status;    /** 任务运行时间表达式 */    private String  cronExpression;    /** 是否异步 */    private boolean  isSync;    /** 任务描述 */    private Long   description;    /** 创建时间 */    private Date    gmtCreate;    /** 修改时间 */    private Date  gmtModify;    //定时发送的方式    private String sendStyle;    //这里方便展示     private String  taskTime;    private String descInfo;    private String org_codes;    private String org_names;    private String publishState;    private String notificationType;    private Strategy strategy;    @Id    @GeneratedValue(strategy=GenerationType.IDENTITY)    @Column(name = "scheduleJobId", nullable = false)    public Long getScheduleJobId() {        return scheduleJobId;    }    public void setScheduleJobId(Long scheduleJobId) {        this.scheduleJobId = scheduleJobId;    }    public String getJobName() {        return jobName;    }    public void setJobName(String jobName) {        this.jobName = jobName;    }    public String getAliasName() {        return aliasName;    }    public void setAliasName(String aliasName) {        this.aliasName = aliasName;    }    public String getJobGroup() {        return jobGroup;    }    public void setJobGroup(String jobGroup) {        this.jobGroup = jobGroup;    }    public String getJobTrigger() {        return jobTrigger;    }    public void setJobTrigger(String jobTrigger) {        this.jobTrigger = jobTrigger;    }    public String getStatus() {        return status;    }    public void setStatus(String status) {        this.status = status;    }    public String getCronExpression() {        return cronExpression;    }    public void setCronExpression(String cronExpression) {        this.cronExpression = cronExpression;    }       public Long getDescription() {return description;}public void setDescription(Long description) {this.description = description;}public Date getGmtCreate() {        return gmtCreate;    }    public void setGmtCreate(Date gmtCreate) {        this.gmtCreate = gmtCreate;    }    public Date getGmtModify() {        return gmtModify;    }    public void setGmtModify(Date gmtModify) {        this.gmtModify = gmtModify;    }    public Boolean getIsSync() {        return isSync;    }    public void setIsSync(Boolean isSync) {        this.isSync = isSync;    }public String getTaskTime() {return taskTime;}public void setTaskTime(String taskTime) {this.taskTime = taskTime;}public void setSync(boolean isSync) {this.isSync = isSync;}public String getSendStyle() {return sendStyle;}public void setSendStyle(String sendStyle) {this.sendStyle = sendStyle;}public String getDescInfo() {return descInfo;}public void setDescInfo(String descInfo) {this.descInfo = descInfo;}public String getOrg_codes() {return org_codes;}public void setOrg_codes(String org_codes) {this.org_codes = org_codes;}public String getPublishState() {return publishState;}public void setPublishState(String publishState) {this.publishState = publishState;}@ManyToOne(cascade = {CascadeType.MERGE,CascadeType.REFRESH }, optional = true) @JoinColumn(name="stratelyId")@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)public Strategy getStrategy() {return strategy;}public void setStrategy(Strategy strategy) {this.strategy = strategy;}public String getNotificationType() {return notificationType;}public void setNotificationType(String notificationType) {this.notificationType = notificationType;}public String getOrg_names() {return org_names;}public void setOrg_names(String org_names) {this.org_names = org_names;}    }


ScheduleJobInit:
package com.jetsen.quartz.event;import javax.annotation.PostConstruct;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import com.jetsen.quartz.service.ScheduleJobService;/** * 定时任务初始化 * @author LY * @date 2016-07-25 */@Componentpublic class ScheduleJobInit {    /** 日志对象 */    private static final Logger LOG = LoggerFactory.getLogger(ScheduleJobInit.class);    /** 定时任务service */    @Autowired    private ScheduleJobService  scheduleJobService;    /**     * 项目启动时初始化     */    @PostConstruct    public void init() {        if (LOG.isInfoEnabled()) {            LOG.info("init");        }        scheduleJobService.initScheduleJob();        if (LOG.isInfoEnabled()) {            LOG.info("end");        }    }}
ScheduleException:


package com.jetsen.quartz.exceptions;import com.dexcoder.commons.exceptions.DexcoderException;/** * 自定义异常 * @author LY * @date 2016-07-25 */public class ScheduleException extends DexcoderException {    /** serialVersionUID */    private static final long serialVersionUID = -1921648378954132894L;    /**     * Instantiates a new ScheduleException.     *     * @param e the e     */    public ScheduleException(Throwable e) {        super(e);    }    /**     * Constructor     *     * @param message the message     */    public ScheduleException(String message) {        super(message);    }    /**     * Constructor     *     * @param code the code     * @param message the message     */    public ScheduleException(String code, String message) {        super(code, message);    }}
JobFactory:

package com.jetsen.quartz.factory;import java.util.Date;import java.util.List;import javax.servlet.http.HttpServletRequest;import org.quartz.DisallowConcurrentExecution;import org.quartz.Job;import org.quartz.JobDataMap;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Service;import com.jetsen.common.bean.SpringBeanUtil;import com.jetsen.common.util.StringUtil;import com.jetsen.controller.LibraryController;import com.jetsen.model.book.Book;import com.jetsen.model.cms.Manuscript;import com.jetsen.quartz.entity.ScheduleJob;import com.jetsen.quartz.service.ScheduleJobService;import com.jetsen.quartz.vo.ScheduleJobVo;import com.jetsen.service.BookService;import com.jetsen.service.ManuscriptService;/** * 任务工厂类,非同步 * @author LY * @date 2016-07-25 */@DisallowConcurrentExecutionpublic class JobFactory implements Job {    /* 日志对象 */    private static final Logger LOG = LoggerFactory.getLogger(JobFactory.class);    public void execute(JobExecutionContext context) throws JobExecutionException {        LOG.info("JobFactory execute");        /*ScheduleJob scheduleJob = (ScheduleJob) context.getMergedJobDataMap().get(            ScheduleJobVo.JOB_PARAM_KEY);*/        ManuscriptService manuscriptService = (ManuscriptService) SpringBeanUtil.getBean("jcManuscriptService");        BookService companybookService = (BookService) SpringBeanUtil.getBean("bookService");        ScheduleJobService scheduleJobService = (ScheduleJobService) SpringBeanUtil.getBean("scheduleJobService");        JobDataMap dataMap = context.getJobDetail().getJobDataMap();Long ids = dataMap.getLong("jobParam");//Manuscript content = manuscriptService.getManuScriptByTask(ids);String library = dataMap.getString("library");String issue = dataMap.getString("issue");String books = dataMap.getString("book");if(library!=null){String publishStatus = dataMap.getString("publishStatus");if(library.equals("library") ||  "liarary".equals(library)){List<Book> bookList = companybookService.getBookList(1,publishStatus);if(bookList!=null && bookList.size()>0){String bookIds = "";for (Book book : bookList) { bookIds += book.getBookid()+","; //companybookService.updateIsSend(2, bookIds);}//scheduleJobService.updateStatus("0");companybookService.send(null, null, null, null, null,bookIds);}}}if(issue!=null){String publishStatus = dataMap.getString("publishStatus");if(issue.equals("issue") ||  "issue".equals(issue)){List<Book> bookList = companybookService.getBookList(1,publishStatus);if(bookList!=null && bookList.size()>0){String bookIds = "";for (Book book : bookList) { bookIds += book.getBookid()+","; //companybookService.updateIsSend(2, bookIds);}//scheduleJobService.updateStatus("0");companybookService.send(null, null, null, null, null,bookIds);}}}if(books!=null){String org_codes = dataMap.getString("org_codes");String publishStatus = dataMap.getString("publishStatus");String notificationType = dataMap.getString("notificationType");if(books.equals("book") || "book".equals(books)){List<Book> bookList = companybookService.getBookList(0,publishStatus);if(bookList!=null && bookList.size()>0){String bookIds = "";for (Book book : bookList) { bookIds += book.getBookid()+",";// companybookService.updateIsSend(1, bookIds);}companybookService.bookSend(notificationType,org_codes,bookIds);//scheduleJobService.updateStatus("0");}}}if(ids!=0L){ manuscriptService.publishSingleState(1, new Date(), ids); scheduleJobService.updateInfoStatus("0", ids);}        try {            Thread.sleep(3000);        } catch (InterruptedException e) {            e.printStackTrace();        }    }}
JobSyncFactory:

package com.jetsen.quartz.factory;import java.util.Date;import java.util.List;import org.quartz.Job;import org.quartz.JobDataMap;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.jetsen.common.bean.SpringBeanUtil;import com.jetsen.model.book.Book;import com.jetsen.quartz.service.ScheduleJobService;import com.jetsen.service.BookService;import com.jetsen.service.ManuscriptService;/** * 同步的任务工厂类 * @author LY * @date 2016-07-25 */public class JobSyncFactory implements Job {    private static final Logger LOG = LoggerFactory.getLogger(JobSyncFactory.class);    public void execute(JobExecutionContext context) throws JobExecutionException {        LOG.info("JobSyncFactory execute");       /* JobDataMap mergedJobDataMap = jobExecutionContext.getMergedJobDataMap();        ScheduleJob scheduleJob = (ScheduleJob) mergedJobDataMap.get(ScheduleJobVo.JOB_PARAM_KEY);        System.out.println("jobName:" + scheduleJob.getJobName() + "  " + scheduleJob);*/                ManuscriptService manuscriptService = (ManuscriptService) SpringBeanUtil.getBean("jcManuscriptService");        BookService companybookService = (BookService) SpringBeanUtil.getBean("bookService");        ScheduleJobService scheduleJobService = (ScheduleJobService) SpringBeanUtil.getBean("scheduleJobService");        JobDataMap dataMap = context.getJobDetail().getJobDataMap();Long ids = dataMap.getLong("jobParam");//Manuscript content = manuscriptService.getManuScriptByTask(ids);String library = dataMap.getString("library");String issue = dataMap.getString("issue");String books = dataMap.getString("book");if(library!=null){//String publishStatus = dataMap.getString("publishStatus");if(library.equals("library") ||  "liarary".equals(library)){List<Book> bookList = companybookService.getBookList(1);if(bookList!=null && bookList.size()>0){String bookIds = "";for (Book book : bookList) { bookIds += book.getBookid()+","; //companybookService.updateIsSend(2, bookIds);}//scheduleJobService.updateStatus("0");companybookService.send(null, null, null, null, null,bookIds);}}}if(issue!=null){//String publishStatus = dataMap.getString("publishStatus");if(issue.equals("issue") ||  "issue".equals(issue)){List<Book> bookList = companybookService.getBookList(1);if(bookList!=null && bookList.size()>0){String bookIds = "";for (Book book : bookList) { bookIds += book.getBookid()+","; //companybookService.updateIsSend(2, bookIds);}//scheduleJobService.updateStatus("0");companybookService.send(null, null, null, null, null,bookIds);}}}if(books!=null){String org_codes = dataMap.getString("org_codes");String publishStatus = dataMap.getString("publishStatus");String notificationType = dataMap.getString("notificationType");if(books.equals("book") || "book".equals(books)){List<Book> bookList = companybookService.getBookList(0,publishStatus);if(bookList!=null && bookList.size()>0){String bookIds = "";for (Book book : bookList) { bookIds += book.getBookid()+",";// companybookService.updateIsSend(1, bookIds);}companybookService.bookSend(notificationType,org_codes,bookIds);//scheduleJobService.updateStatus("0");}}}if(ids!=null && ids!=0){ manuscriptService.publishSingleState(1, new Date(), ids); scheduleJobService.updateInfoStatus("0", ids);}        try {            Thread.sleep(3000);        } catch (InterruptedException e) {            e.printStackTrace();        }    }}

说明:同步方法:比如说我定时了固定的时候,设置了好几个,都是在这个时间执行,那就要走同步方法才可以;非同步方法,是设置一个时间点,跟其他不冲突,这个没有问题,这里是要注意的地方,然后这俩方法可以加入自己想要执行的业务逻辑,这里只需知道怎么传递参数过来就行了,比如我判断了,或者传过来id啦,这里都可以的。

JobDataMap dataMap = context.getJobDetail().getJobDataMap();Long ids = dataMap.getLong("jobParam");String library = dataMap.getString("library");
这里可以接收不同的类型,比如我这里获取id用long来接收,而根据不同平台进行判断是string来接收参数。

ScheduleJobService:

package com.jetsen.quartz.service;import java.util.List;import com.jetsen.quartz.entity.ScheduleJob;import com.jetsen.quartz.vo.ScheduleJobVo;/** * 定时任务service * @author LY * @date 2016-07-25 */public interface ScheduleJobService {    /**     * 初始化定时任务     */    public void initScheduleJob();    /**     * 新增(这里参加增加是Mq的机构码)     * @param scheduleJobVo     * @return     */    public void insert(ScheduleJobVo scheduleJobVo);    /**     * 直接修改 只能修改运行的时间,参数、同异步等无法修改     *      * @param scheduleJobVo     */    public void update(ScheduleJobVo scheduleJobVos);    /**     * 删除重新创建方式     *      * @param scheduleJobVo     */    public void delUpdate(ScheduleJobVo scheduleJobVo);    /**     * 删除     *      * @param scheduleJobId     */    public void delete(Long scheduleJobId);    /**     * 运行一次任务     *     * @param scheduleJobId the schedule job id     * @return     */    public void runOnce(Long scheduleJobId);    /**     * 暂停任务     *     * @param scheduleJobId the schedule job id     * @return     */    public void pauseJob(Long scheduleJobId);    /**     * 恢复任务     *     * @param scheduleJobId the schedule job id     * @return     */    public void resumeJob(Long scheduleJobId);    /**     * 获取任务对象     *      * @param scheduleJobId     * @return     */    public ScheduleJobVo get(Long scheduleJobId);    /**     * 查询任务列表     *      * @param scheduleJobVo     * @return     */    public List<ScheduleJobVo> queryList(ScheduleJobVo scheduleJobVo);    /**     * 获取运行中的任务列表     *     * @return     */    public List<ScheduleJobVo> queryExecutingJobList();    /**     * 修改状态     * @param status     */    public void updateStatus(String status,Long scheduleJobId);    /**     * 修改状态     * @param status     */    public void updateInfoStatus(String status,Long scheduleJobId);            /**     * 根据发送状态查重     * @param sendStyle     * @return     */    public List<ScheduleJobVo> findByStyle(String sendStyle);        /**     * 根据id查询定时任务     * @param id     * @return     */    public List<ScheduleJobVo> findById(Long id);    /**     * 更新按钮参数     * @param desc     * @param sid     */    public void updateDesc(Long desc,Long sid);    /**     * 根据策略id删除定时任务     * @param sid     */    public void deleteBySid(Long sid);}

ScheduleJobServiceImpl:

package com.jetsen.quartz.service.impl;import java.util.ArrayList;import java.util.List;import org.quartz.CronTrigger;import org.quartz.JobDetail;import org.quartz.JobExecutionContext;import org.quartz.JobKey;import org.quartz.Scheduler;import org.quartz.SchedulerException;import org.quartz.Trigger;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.dexcoder.commons.bean.BeanConverter;import com.jetsen.quartz.entity.ScheduleJob;import com.jetsen.quartz.service.ScheduleJobService;import com.jetsen.quartz.util.ScheduleUtils;import com.jetsen.quartz.vo.ScheduleJobVo;import com.jetsen.repository.SchedulejobRepository;/** * 定时任务 * @author LY * @date 2016-07-25 */@Service("scheduleJobService")public class ScheduleJobServiceImpl implements ScheduleJobService {    /** 调度工厂Bean */    @Autowired    private Scheduler scheduler;    @Autowired    private SchedulejobRepository   schedulejobRepository;    public void initScheduleJob() {        List<ScheduleJob> scheduleJobList = schedulejobRepository.findAll();        if (scheduleJobList==null) {            return;        }        for (ScheduleJob scheduleJob : scheduleJobList) {            CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getJobName(),                scheduleJob.getJobGroup());                                    if(scheduleJob.getStatus().equals("1")){            //不存在,创建一个                if (cronTrigger == null) {                    ScheduleUtils.createScheduleJob(scheduler, scheduleJob);                } else {                    //已存在,那么更新相应的定时设置                    ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);                }            }                    }    }    public void insert(ScheduleJobVo scheduleJobVo) {        ScheduleJob scheduleJob = scheduleJobVo.getTargetObject(ScheduleJob.class);        ScheduleUtils.createScheduleJob(scheduler, scheduleJob);        if(scheduleJob.getSendStyle()!=null){        if(scheduleJobVo.getSendStyle().equals("job-library") || scheduleJobVo.getSendStyle().equals("job-library")){            schedulejobRepository.save(scheduleJob);            }            if(scheduleJobVo.getSendStyle().equals("job-issue") || scheduleJobVo.getSendStyle().equals("job-issue")){            schedulejobRepository.save(scheduleJob);            }            if(scheduleJobVo.getSendStyle().equals("job-book") || scheduleJobVo.getSendStyle().equals("job-book")){            schedulejobRepository.save(scheduleJob);            }        }            }    @Override    public void update(ScheduleJobVo scheduleJobVo) {        ScheduleJob scheduleJob = scheduleJobVo.getTargetObject(ScheduleJob.class);        ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);        if(scheduleJob.getSendStyle()!=null){        if(scheduleJobVo.getSendStyle().equals("job-library") || scheduleJobVo.getSendStyle().equals("job-library")){            schedulejobRepository.save(scheduleJob);            }            if(scheduleJobVo.getSendStyle().equals("job-issue") || scheduleJobVo.getSendStyle().equals("job-issue")){            schedulejobRepository.save(scheduleJob);            }            if(scheduleJobVo.getSendStyle().equals("other") || scheduleJobVo.getSendStyle().equals("other")){            schedulejobRepository.save(scheduleJob);            }            if(scheduleJobVo.getSendStyle().equals("job-book") || scheduleJobVo.getSendStyle().equals("job-book")){            schedulejobRepository.save(scheduleJob);            }        }    }    public void delUpdate(ScheduleJobVo scheduleJobVo) {        ScheduleJob scheduleJob = scheduleJobVo.getTargetObject(ScheduleJob.class);        //先删除        ScheduleUtils.deleteScheduleJob(scheduler, scheduleJob.getJobName(), scheduleJob.getJobGroup());        //再创建        ScheduleUtils.createScheduleJob(scheduler, scheduleJob);        if(scheduleJob.getSendStyle()!=null){        if(scheduleJobVo.getSendStyle().equals("job-library") || scheduleJobVo.getSendStyle().equals("job-library")){            schedulejobRepository.save(scheduleJob);            }            if(scheduleJobVo.getSendStyle().equals("job-issue") || scheduleJobVo.getSendStyle().equals("job-issue")){            schedulejobRepository.save(scheduleJob);            }            if(scheduleJobVo.getSendStyle().equals("job-book") || scheduleJobVo.getSendStyle().equals("job-book")){            schedulejobRepository.save(scheduleJob);            }        }    }    public void delete(Long scheduleJobId) {        ScheduleJob scheduleJob = schedulejobRepository.findOne(scheduleJobId);        //删除运行的任务        ScheduleUtils.deleteScheduleJob(scheduler, scheduleJob.getJobName(), scheduleJob.getJobGroup());        //删除数据        //schedulejobRepository.delete(scheduleJobId);    }    public void runOnce(Long scheduleJobId) {        ScheduleJob scheduleJob = schedulejobRepository.findOne(scheduleJobId);        ScheduleUtils.runOnce(scheduler, scheduleJob.getJobName(), scheduleJob.getJobGroup());    }    public void pauseJob(Long scheduleJobId) {        ScheduleJob scheduleJob = schedulejobRepository.findOne(scheduleJobId);        ScheduleUtils.pauseJob(scheduler, scheduleJob.getJobName(), scheduleJob.getJobGroup());        //演示数据库就不更新了    }    public void resumeJob(Long scheduleJobId) {        ScheduleJob scheduleJob = schedulejobRepository.findOne(scheduleJobId);        ScheduleUtils.resumeJob(scheduler, scheduleJob.getJobName(), scheduleJob.getJobGroup());        //演示数据库就不更新了    }    //这里是vo不知道为什么    /*public ScheduleJobVo get(Long scheduleJobId) {        ScheduleJobVo scheduleJob = schedulejobRepository.findOne(scheduleJobId);        return scheduleJob;    }*/    public List<ScheduleJobVo> queryList(ScheduleJobVo scheduleJobVo) {        List<ScheduleJob> scheduleJobs = schedulejobRepository.findAll();        List<ScheduleJobVo> scheduleJobVoList = BeanConverter.convert(ScheduleJobVo.class, scheduleJobs);        try {            for (ScheduleJobVo vo : scheduleJobVoList) {                JobKey jobKey = ScheduleUtils.getJobKey(vo.getJobName(), vo.getJobGroup());                List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);                if (triggers.size()==0) {                    continue;                }                //这里一个任务可以有多个触发器, 但是我们一个任务对应一个触发器,所以只取第一个即可,清晰明了                Trigger trigger = triggers.iterator().next();                scheduleJobVo.setJobTrigger(trigger.getKey().getName());                Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());                vo.setStatus(triggerState.name());                if (trigger instanceof CronTrigger) {                    CronTrigger cronTrigger = (CronTrigger) trigger;                    String cronExpression = cronTrigger.getCronExpression();                    vo.setCronExpression(cronExpression);                }            }        } catch (SchedulerException e) {            //演示用,就不处理了        }        return scheduleJobVoList;    }    public List<ScheduleJobVo> queryExecutingJobList() {        try {            List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();            List<ScheduleJobVo> jobList = new ArrayList<ScheduleJobVo>(executingJobs.size());            for (JobExecutionContext executingJob : executingJobs) {                ScheduleJobVo job = new ScheduleJobVo();                JobDetail jobDetail = executingJob.getJobDetail();                JobKey jobKey = jobDetail.getKey();                Trigger trigger = executingJob.getTrigger();                job.setJobName(jobKey.getName());                job.setJobGroup(jobKey.getGroup());                job.setJobTrigger(trigger.getKey().getName());                Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());                job.setStatus(triggerState.name());                if (trigger instanceof CronTrigger) {                    CronTrigger cronTrigger = (CronTrigger) trigger;                    String cronExpression = cronTrigger.getCronExpression();                    job.setCronExpression(cronExpression);                }                jobList.add(job);            }            return jobList;        } catch (SchedulerException e) {            //演示用,就不处理了            return null;        }    }@Overridepublic ScheduleJobVo get(Long scheduleJobId) {return schedulejobRepository.findById(scheduleJobId);}@Overridepublic void updateStatus(String status,Long scheduleJobId) {schedulejobRepository.updateStatus(status,scheduleJobId);}@Overridepublic List<ScheduleJobVo> findByStyle(String sendStyle) {return schedulejobRepository.findByStyle(sendStyle);}@Overridepublic void updateDesc(Long desc, Long sid) {schedulejobRepository.updateStatus(desc, sid);}@Overridepublic List<ScheduleJobVo> findById(Long id) {return schedulejobRepository.findBySId(id);}@Overridepublic void deleteBySid(Long sid) {schedulejobRepository.delete_strategy(sid);}@Overridepublic void updateInfoStatus(String status, Long scheduleJobId) {schedulejobRepository.updateInfoStatus(status, scheduleJobId);}}

ScheduleUtils:

package com.jetsen.quartz.util;import org.quartz.CronScheduleBuilder;import org.quartz.CronTrigger;import org.quartz.Job;import org.quartz.JobBuilder;import org.quartz.JobDetail;import org.quartz.JobKey;import org.quartz.Scheduler;import org.quartz.SchedulerException;import org.quartz.TriggerBuilder;import org.quartz.TriggerKey;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.jetsen.quartz.entity.ScheduleJob;import com.jetsen.quartz.exceptions.ScheduleException;import com.jetsen.quartz.factory.JobFactory;import com.jetsen.quartz.factory.JobSyncFactory;import com.jetsen.quartz.vo.ScheduleJobVo;/** * 定时任务辅助类 * @author LY * @date 2016-07-25 */public class ScheduleUtils {    /** 日志对象 */    private static final Logger LOG = LoggerFactory.getLogger(ScheduleUtils.class);    /**     * 获取触发器key     *      * @param jobName     * @param jobGroup     * @return     */    public static TriggerKey getTriggerKey(String jobName, String jobGroup) {        return TriggerKey.triggerKey(jobName, jobGroup);    }    /**     * 获取表达式触发器     *     * @param scheduler the scheduler     * @param jobName the job name     * @param jobGroup the job group     * @return cron trigger     */    public static CronTrigger getCronTrigger(Scheduler scheduler, String jobName, String jobGroup) {        try {            TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);            return (CronTrigger) scheduler.getTrigger(triggerKey);        } catch (SchedulerException e) {            LOG.info("获取定时任务CronTrigger出现异常", e);            throw new ScheduleException("获取定时任务CronTrigger出现异常");        }    }    /**     * 创建任务     *     * @param scheduler the scheduler     * @param scheduleJob the schedule job     */    public static void createScheduleJob(Scheduler scheduler, ScheduleJob scheduleJob) {        createScheduleJob(scheduler, scheduleJob.getJobName(), scheduleJob.getJobGroup(),            scheduleJob.getCronExpression(), scheduleJob.getIsSync(), scheduleJob.getDescription(),scheduleJob.getStatus(),scheduleJob.getSendStyle(),scheduleJob.getOrg_codes(),scheduleJob.getPublishState(),scheduleJob.getNotificationType());    }    /**     * 创建定时任务     *     * @param scheduler the scheduler     * @param jobName the job name     * @param jobGroup the job group     * @param cronExpression the cron expression     * @param isSync the is sync     * @param param the param     */    public static void createScheduleJob(Scheduler scheduler, String jobName, String jobGroup,                                         String cronExpression, boolean isSync, Long param,String status,String sendStyle,String org_codes,String publishStatus,String notificationType) {        //同步或异步        Class<? extends Job> jobClass = isSync ? JobSyncFactory.class : JobFactory.class;        //构建job信息        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroup).build();        if(param!=null){        //放入参数,运行时的方法可以获取            jobDetail.getJobDataMap().put(ScheduleJobVo.JOB_PARAM_KEY, param);        }else{         Long paramValue = 0L;         jobDetail.getJobDataMap().put(ScheduleJobVo.JOB_PARAM_KEY, paramValue);        }                if(sendStyle!=null){         if(sendStyle.equals("job-library") || "job-library".equals(sendStyle)){             jobDetail.getJobDataMap().put("library", "library");             }             if(sendStyle.equals("job-issue") || "job-issue".equals(sendStyle)){             jobDetail.getJobDataMap().put("issue", "issue");             }             if(sendStyle.equals("job-book") || "job-book".equals(sendStyle)){            jobDetail.getJobDataMap().put("book", "book");             }        }        if(org_codes!=null){        jobDetail.getJobDataMap().put("org_codes", org_codes);        }        if(publishStatus!=null){        jobDetail.getJobDataMap().put("publishStatus", publishStatus);        }        if(notificationType!=null){        jobDetail.getJobDataMap().put("notificationType", notificationType);        }        //表达式调度构建器        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);        //按新的cronExpression表达式构建一个新的trigger        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroup)            .withSchedule(scheduleBuilder).build();        try {        if(status.equals("1")){        scheduler.scheduleJob(jobDetail, trigger);        }        } catch (SchedulerException e) {            LOG.info("创建定时任务失败", e);            throw new ScheduleException("创建定时任务失败");        }    }    /**     * 运行一次任务     *      * @param scheduler     * @param jobName     * @param jobGroup     */    public static void runOnce(Scheduler scheduler, String jobName, String jobGroup) {        JobKey jobKey = JobKey.jobKey(jobName, jobGroup);        try {            scheduler.triggerJob(jobKey);        } catch (SchedulerException e) {            LOG.info("运行一次定时任务失败", e);            throw new ScheduleException("运行一次定时任务失败");        }    }    /**     * 暂停任务     *      * @param scheduler     * @param jobName     * @param jobGroup     */    public static void pauseJob(Scheduler scheduler, String jobName, String jobGroup) {        JobKey jobKey = JobKey.jobKey(jobName, jobGroup);        try {            scheduler.pauseJob(jobKey);        } catch (SchedulerException e) {            LOG.info("暂停定时任务失败", e);            throw new ScheduleException("暂停定时任务失败");        }    }    /**     * 恢复任务     *     * @param scheduler     * @param jobName     * @param jobGroup     */    public static void resumeJob(Scheduler scheduler, String jobName, String jobGroup) {        JobKey jobKey = JobKey.jobKey(jobName, jobGroup);        try {            scheduler.resumeJob(jobKey);        } catch (SchedulerException e) {            LOG.info("暂停定时任务失败", e);            throw new ScheduleException("暂停定时任务失败");        }    }    /**     * 获取jobKey     *     * @param jobName the job name     * @param jobGroup the job group     * @return the job key     */    public static JobKey getJobKey(String jobName, String jobGroup) {        return JobKey.jobKey(jobName, jobGroup);    }    /**     * 更新定时任务     *     * @param scheduler the scheduler     * @param scheduleJob the schedule job     */    public static void updateScheduleJob(Scheduler scheduler, ScheduleJob scheduleJob) {        updateScheduleJob(scheduler, scheduleJob.getJobName(), scheduleJob.getJobGroup(),            scheduleJob.getCronExpression(), scheduleJob.getIsSync(), scheduleJob);    }    /**     * 更新定时任务     *     * @param scheduler the scheduler     * @param jobName the job name     * @param jobGroup the job group     * @param cronExpression the cron expression     * @param isSync the is sync     * @param param the param     */    public static void updateScheduleJob(Scheduler scheduler, String jobName, String jobGroup,                                         String cronExpression, boolean isSync, Object param) {        //同步或异步//        Class<? extends Job> jobClass = isSync ? JobSyncFactory.class : JobFactory.class;        try {//            JobDetail jobDetail = scheduler.getJobDetail(getJobKey(jobName, jobGroup));//            jobDetail = jobDetail.getJobBuilder().ofType(jobClass).build();            //更新参数 实际测试中发现无法更新//            JobDataMap jobDataMap = jobDetail.getJobDataMap();//            jobDataMap.put(ScheduleJobVo.JOB_PARAM_KEY, param);//            jobDetail.getJobBuilder().usingJobData(jobDataMap);            TriggerKey triggerKey = ScheduleUtils.getTriggerKey(jobName, jobGroup);            //表达式调度构建器            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);            //按新的cronExpression表达式重新构建trigger            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder)                .build();            //按新的trigger重新设置job执行            scheduler.rescheduleJob(triggerKey, trigger);        } catch (SchedulerException e) {            LOG.info("更新定时任务失败", e);            throw new ScheduleException("更新定时任务失败");        }    }    /**     * 删除定时任务     *     * @param scheduler     * @param jobName     * @param jobGroup     */    public static void deleteScheduleJob(Scheduler scheduler, String jobName, String jobGroup) {        try {            scheduler.deleteJob(getJobKey(jobName, jobGroup));        } catch (SchedulerException e) {            LOG.info("删除定时任务失败", e);            throw new ScheduleException("删除定时任务失败");        }    }}

说明:看,这里的jobDetail.getJobDataMap().put("library", "library");就是将你想传递的参数进行put压值

ScheduleJobVo:

package com.jetsen.quartz.vo;import java.util.Date;import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.ManyToOne;import javax.persistence.Table;import org.hibernate.annotations.Cache;import org.hibernate.annotations.CacheConcurrencyStrategy;import com.dexcoder.commons.pager.Pageable;import com.jetsen.model.book.Strategy;/** * @author LY * @date 2016-07-25 */@Entity@Table(name = "task_scheduleJob")public class ScheduleJobVo extends Pageable {    private static final long  serialVersionUID = -4216107640768329946L;    /** 任务调度的参数key */    public static final String JOB_PARAM_KEY    = "jobParam";    /** 任务id */    private Long               scheduleJobId;    /** 任务名称 */    private String             jobName;    /** 任务别名 */    private String             aliasName;    /** 任务分组 */    private String             jobGroup;    /** 触发器 */    private String             jobTrigger;    /** 任务状态 */    private String             status;    /** 任务运行时间表达式 */    private String             cronExpression;    /** 是否异步 */    private boolean            isSync;    /** 任务描述 */    private Long             description;    /** 创建时间 */    private Date               gmtCreate;    /** 修改时间 */    private Date               gmtModify;    //发送方式    private String  sendStyle;    //这里方便展示     private String  taskTime;    private String descInfo;    /** 定时的机构编码封装在表中方便传递*/    private String org_codes;    private String org_names;    private String publishState;//出版状态    private String notificationType;    private Strategy strategy;    @Id    @GeneratedValue(strategy=GenerationType.IDENTITY)    @Column(name = "scheduleJobId", nullable = false)    public Long getScheduleJobId() {        return scheduleJobId;    }    public void setScheduleJobId(Long scheduleJobId) {        this.scheduleJobId = scheduleJobId;    }    public String getJobName() {        return jobName;    }    public void setJobName(String jobName) {        this.jobName = jobName;    }    public String getAliasName() {        return aliasName;    }    public void setAliasName(String aliasName) {        this.aliasName = aliasName;    }    public String getJobGroup() {        return jobGroup;    }    public void setJobGroup(String jobGroup) {        this.jobGroup = jobGroup;    }    public String getJobTrigger() {        return jobTrigger;    }    public void setJobTrigger(String jobTrigger) {        this.jobTrigger = jobTrigger;    }    public String getStatus() {        return status;    }    public void setStatus(String status) {        this.status = status;    }    public String getCronExpression() {        return cronExpression;    }    public void setCronExpression(String cronExpression) {        this.cronExpression = cronExpression;    }        public Long getDescription() {return description;}public void setDescription(Long description) {this.description = description;}public void setSync(boolean isSync) {this.isSync = isSync;}public Date getGmtCreate() {        return gmtCreate;    }    public void setGmtCreate(Date gmtCreate) {        this.gmtCreate = gmtCreate;    }    public Date getGmtModify() {        return gmtModify;    }    public void setGmtModify(Date gmtModify) {        this.gmtModify = gmtModify;    }    public Boolean getIsSync() {        return isSync;    }    public void setIsSync(Boolean isSync) {        this.isSync = isSync;    }public String getTaskTime() {return taskTime;}public void setTaskTime(String taskTime) {this.taskTime = taskTime;}public String getSendStyle() {return sendStyle;}public void setSendStyle(String sendStyle) {this.sendStyle = sendStyle;}public String getDescInfo() {return descInfo;}public void setDescInfo(String descInfo) {this.descInfo = descInfo;}public String getOrg_codes() {return org_codes;}public void setOrg_codes(String org_codes) {this.org_codes = org_codes;}public String getPublishState() {return publishState;}public void setPublishState(String publishState) {this.publishState = publishState;}@ManyToOne(cascade = {CascadeType.MERGE,CascadeType.REFRESH }, optional = true) @JoinColumn(name="stratelyId")@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)public Strategy getStrategy() {return strategy;}public void setStrategy(Strategy strategy) {this.strategy = strategy;}public String getNotificationType() {return notificationType;}public void setNotificationType(String notificationType) {this.notificationType = notificationType;}public String getOrg_names() {return org_names;}public void setOrg_names(String org_names) {this.org_names = org_names;}        }

StrategyController(实现的controller):

@RequestMapping("/saveScheduleSend")    public String saveScheduleSend(String times,String org_codes,String strategyName,String org_name,RedirectAttributes redirectAttributes,String[] englishName,    String publish_status,String notification_type,String taskSwitch,Long sid,String type,String style) throws Exception{String task = "";/*if(times.indexOf(",")>0){task = times.substring(0,times.length() - 1);}else{task = times;}*//*if(org_name.indexOf(",")>0){org_name = org_name.substring(1, org_name.length());}*/if(style.equals("edit") && "edit".equals(style)){if (times.lastIndexOf(",")>0) {task = times.substring(0,times.length() - 1);}else if(times.startsWith(",")){task = times.substring(1, times.length());}else{task = times;}}else{task = times.substring(0,times.length() - 1);}//SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");List<ScheduleJobVo> jobList = scheduleJobService.findById(sid);ScheduleJobVo job = new ScheduleJobVo();//if(task!=null && !"".equals(task)){//String[] time = task.split(",");//for (int i = 0; i < time.length; i++) {String express = "";String[] time = task.split(",");String hour = "";String minute = "";for (int i = 0; i < time.length; i++) {String one[] = time[i].split(":");hour+=one[0]+",";minute+=one[1]+",";}hour = hour.substring(0,hour.length()-1);minute = minute.substring(0,minute.length()-1);express = minute+" "+hour;/*if(task!=null && !"".equals(task)){String[] time = task.split(",");for (int i = 0; i < time.length; i++) {String[] minutes = task.split(":");Date date = sdf.parse(time[i]);minut}}*///express = express.substring(0, express.length()-1);String cron = "";String desc = "";String descInfo = "";if(englishName!=null){List<Columns> cList = columnsService.getColumnsByEnglish(englishName);for (Columns columns : cList) {desc += columns.getColumnName()+",";}desc = desc.substring(0, desc.length()-1);String newName = "";for (int j = 0; j < englishName.length; j++) {newName += englishName[j]+",";}newName = newName.substring(0, newName.length()-1);cron = "0 "+express+" ? *"+" "+newName;descInfo = desc;}else{cron = "0 "+express+" * * ?";descInfo = "星期一,星期二,星期三,星期四,星期五,星期六,星期日";}String uuid = UUID.getUUID();job.setJobName(uuid);job.setJobGroup("group"+1);job.setAliasName("alias"+1);job.setStatus("0");if(taskSwitch!=null && !"".equals(taskSwitch)){if(taskSwitch.equals("开") || "开".equals(taskSwitch)){job.setDescription(1L);}else{job.setDescription(0L);}}if(jobList!=null && jobList.size()>0){for (ScheduleJobVo scheduleJobVo : jobList) {scheduleJobVo.setJobName(uuid);scheduleJobVo.setJobGroup("group"+1);scheduleJobVo.setAliasName("alias"+1);scheduleJobVo.setStatus("0");scheduleJobVo.setDescInfo(descInfo);scheduleJobVo.setCronExpression(cron);scheduleJobVo.setIsSync(true);if(taskSwitch!=null && !"".equals(taskSwitch)){scheduleJobVo.setDescription(1L);}else{scheduleJobVo.setDescription(0L);}Strategy strategy = strategyService.findById(sid);if(strategy!=null){strategy.setPublishStatus(publish_status);strategy.setNotificationType(notification_type);strategy.setSwitchStatus("0");strategy.setStrategyStyle(strategyName);scheduleJobVo.setStrategy(strategy);}scheduleJobVo.setPublishState(publish_status);scheduleJobVo.setNotificationType(notification_type);scheduleJobVo.setTaskTime(task);scheduleJobVo.setSendStyle(type);scheduleJobVo.setOrg_codes(org_codes);scheduleJobVo.setOrg_names(org_name);scheduleJobService.delUpdate(scheduleJobVo);}}else{job.setDescInfo(descInfo);//String cron=getCron(date);job.setPublishState(publish_status);job.setNotificationType(notification_type);job.setCronExpression(cron);job.setIsSync(true);job.setSendStyle(type);job.setOrg_codes(org_codes);job.setOrg_names(org_name);Strategy strategy = new Strategy();strategy.setSwitchStatus("0");strategy.setPublishStatus(publish_status);strategy.setNotificationType(notification_type);strategy.setStrategyStyle(strategyName);strategyService.doAdd(strategy);job.setStrategy(strategy);if(org_name!=null && !"".equals(org_name)){String[] orgName = org_name.split(",");for (int k = 0; k < orgName.length; k++) {String[] orgCode = org_codes.split(",");ConfigOrganization organization = new ConfigOrganization();organization.setOrgName(orgName[k]);organization.setOrgCode(orgCode[k]);organization.setStrategy(strategy);configOrganizationService.addOrganization(organization);   }}job.setTaskTime(task);scheduleJobService.insert(job);}//}//job.setTaskTime(time);//}//String[] names = descInfo.split(",");/*columnsService.updateStatus(0);columnsService.updateStatus(1, names);*///configOrganizationService.delete();return "redirect:/strategy/schedule?type="+type;    }

接下来,在这个controller里写了时间格式的转换的方法:

public static String getCron(java.util.Date  date){      //String dateFormat="ss mm HH dd MM ? yyyy";  String dateFormat = "0 mm HH * * ?";    return formatDateByPattern(date, dateFormat);   }  public static String getDayCron(java.util.Date  date){      //String dateFormat="ss mm HH dd MM ? yyyy";  //String dateFormat = "0 mm HH ? *";String dateFormat = "mm HH";return formatDateByPattern(date, dateFormat);  }public static String getMinuteCron(java.util.Date  date){      //String dateFormat="ss mm HH dd MM ? yyyy";  //String dateFormat = "0 mm HH ? *";String dateFormat = "mm";return formatDateByPattern(date, dateFormat);  }public static String getHourCron(java.util.Date  date){      //String dateFormat="ss mm HH dd MM ? yyyy";  //String dateFormat = "0 mm HH ? *";String dateFormat = "HH";return formatDateByPattern(date, dateFormat);   }


spring-quartz.xml(这里需要添加配置文件):

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">    <bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"/></beans>


这里列出了我在项目中实现代码,如果需求相似,可以按照这个路线来,中心思想是跟我写的任务(一)时一个道理,这里主要依赖于Quartz框架。





2 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 脚底长鸡眼很痒怎么办 小脚趾上长鸡眼怎么办 6岁宝宝不爱学习怎么办 上班站久了腿肿怎么办 站时间长了腿肿怎么办 孩子做作业老是粗心大意怎么办 高中孩子没学习兴趣怎么办 初三孩子失去学习兴趣怎么办 初二对学习兴趣不大怎么办 脸上痒发红发肿怎么办 孩子作业拖拉爱丢三落四怎么办 腿肌肉按摩肿了怎么办 孩子上一年级成绩差怎么办 小孩脖子拧筋了怎么办 小孩塑料玩具拧不出来怎么办 一年级孩子做数学题粗心怎么办 手和脚有点肿怎么办 手破了之后肿了怎么办 手指肿了有脓怎么办 宝宝手指红肿有脓怎么办 孩子一听做作业就烦气怎么办 虎皮鹦鹉脚瘸了怎么办 虎皮鹦鹉脚受伤了怎么办 虎皮鹦鹉脚流血了怎么办 虎皮鹦鹉被风扇打到脚怎么办 虎皮鹦鹉脚脱臼了怎么办 孩子作业做得慢怎么办 员工给公司造成损失怎么办 小孩有写不完的作业家长怎么办 一年级孩子作业太粗心怎么办 孩子最近不好好做作业怎么办 工作压力大害怕做不好怎么办 孩子的数算不对怎么办? 孩子计算老是出错怎么办呢 孩子经常计算错误能怎么办 孩子老出现计算错误怎么办 孩子做作业马虎该怎么办 黑笔写错了纸破了怎么办 幼儿园报名写错怎么办名字 中考写错了字怎么办 头发没干想睡觉怎么办