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


声明:本文转载自https://my.oschina.net/u/3705164/blog/3042863,转载目的在于传递更多信息,仅供学习交流之用。如有侵权行为,请联系我,我会及时删除。

初探

Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,它可以与J2EE与J2SE应用程序相结合也可以单独使用。Quartz可以用来创建简单或为运行十个,百个,甚至是好几万个Jobs这样复杂的程序。而我们在写Java程序中经常会写一些定时执行的任务,比如某月的几号去执行一件事,每天的凌晨做些什么,或者每天执行一次什么方法,接下来我把简单的Quartz入门实例放进来,是可以直接运行,是对Quartz的增删改查系列,可以对于初学者,有个大概的了解。

这里直接放代码,看效果:

QuartzManager(增删改查方法):

package com.joyce.quartz;  
  
import org.quartz.CronTrigger;  
import org.quartz.JobDetail;  
import org.quartz.Scheduler;  
import org.quartz.SchedulerFactory;  
import org.quartz.impl.StdSchedulerFactory;  
  
public class QuartzManager {  
    private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();  
    private static String JOB_GROUP_NAME = "EXTJWEB_JOBGROUP_NAME";  
    private static String TRIGGER_GROUP_NAME = "EXTJWEB_TRIGGERGROUP_NAME";  
  
    /** 
     * 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名 
     * @param jobName 任务名 
     * @param cls 任务 
     * @param time 时间设置 
     */  
    @SuppressWarnings("rawtypes")  
    public static void addJob(String jobName, Class cls, String time) {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  
            // 任务名,任务组,任务执行类  
            JobDetail jobDetail = new JobDetail(jobName, JOB_GROUP_NAME, cls);  
            //可以传递参数  
            jobDetail.getJobDataMap().put("param", "railsboy");  
            // 触发器  
            CronTrigger trigger = new CronTrigger(jobName, TRIGGER_GROUP_NAME);  
            // 触发器名,触发器组  
            trigger.setCronExpression(time);  
            // 触发器时间设定  
            sched.scheduleJob(jobDetail, trigger);  
            // 启动  
            if (!sched.isShutdown()) {  
                sched.start();  
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
    /** 
     * 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名) 
     * @param jobName 
     * @param time 
     */  
    @SuppressWarnings("rawtypes")  
    public static void modifyJobTime(String jobName, String time) {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  
            CronTrigger trigger = (CronTrigger) sched.getTrigger(jobName,TRIGGER_GROUP_NAME);  
            if (trigger == null) {  
                return;  
            }  
            String oldTime = trigger.getCronExpression();  
            if (!oldTime.equalsIgnoreCase(time)) {  
                JobDetail jobDetail = sched.getJobDetail(jobName,JOB_GROUP_NAME);  
                Class objJobClass = jobDetail.getJobClass();  
                removeJob(jobName);  
                addJob(jobName, objJobClass, time);  
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
  
  
    /** 
     * 移除一个任务(使用默认的任务组名,触发器名,触发器组名) 
     * @param jobName 
     */  
    public static void removeJob(String jobName) {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  
            sched.pauseTrigger(jobName, TRIGGER_GROUP_NAME);// 停止触发器  
            sched.unscheduleJob(jobName, TRIGGER_GROUP_NAME);// 移除触发器  
            sched.deleteJob(jobName, JOB_GROUP_NAME);// 删除任务  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
  
    /** 
     * 启动所有定时任务 
     */  
    public static void startJobs() {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  
            sched.start();  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
  
    /** 
     * 关闭所有定时任务 
     */  
    public static void shutdownJobs() {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  
            if (!sched.isShutdown()) {  
                sched.shutdown();  
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
}  

QuartzJob(任务执行类):

package com.joyce.quartz;  
  
import java.text.SimpleDateFormat;  
import java.util.Date;  
  
import org.quartz.Job;  
import org.quartz.JobDataMap;  
import org.quartz.JobExecutionContext;  
import org.quartz.JobExecutionException;  
  
/** 
 * 任务执行类 
 */  
public class QuartzJob implements Job {  
  
    @Override  
    public void execute(JobExecutionContext content) throws JobExecutionException {  
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ "★★★★★★★★★★★");    
        String jobName = content.getJobDetail().getName();  
        JobDataMap dataMap = content.getJobDetail().getJobDataMap();  
        String param = dataMap.getString("param");  
        System.out.println("传递的参数是="+param +"任务名字是="+jobName);  
    }  
}  

QuartzTest(定时任务测试类):

package com.joyce.quartz.main;  
  
import java.text.SimpleDateFormat;  
import java.util.Date;  
  
import com.joyce.quartz.QuartzJob;  
import com.joyce.quartz.QuartzManager;  
  
public class QuartzTest {  
    public static void main(String[] args) {  
        try {  
            String job_name = "动态任务调度";  
            System.out.println("【任务启动】开始(每10秒输出一次)...");    
            QuartzManager.addJob(job_name, QuartzJob.class, "0/10 * * * * ?");  
            Thread.sleep(5000);  
            System.out.println("【修改时间】开始(每2秒输出一次)...");    
            QuartzManager.modifyJobTime(job_name, "10/2 * * * * ?");    
            Thread.sleep(6000);    
            System.out.println("【移除定时】开始...");    
            QuartzManager.removeJob(job_name);    
            System.out.println("【移除定时】成功");    
            System.out.println("【再次添加定时任务】开始(每10秒输出一次)...");    
            QuartzManager.addJob(job_name, QuartzJob.class, "*/10 * * * * ?");    
            Thread.sleep(60000);    
            System.out.println("【移除定时】开始...");    
            QuartzManager.removeJob(job_name);    
            System.out.println("【移除定时】成功");  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
      
    public static String formatDateByPattern(Date date,String dateFormat){    
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);    
        String formatTimeStr = null;    
        if (date != null) {    
            formatTimeStr = sdf.format(date);    
        }    
        return formatTimeStr;    
    }    
    public static String getCron(java.util.Date  date){    
        String dateFormat="ss mm HH dd MM ? yyyy";    
        return formatDateByPattern(date, dateFormat);    
     }    
}  

console执行效果:

mylife.png

常用的时间配置:

格式: [秒] [分] [小时] [日] [月] [周] [年]0 0 12 * * ?           
每天12点触发 0 15 10 ? * *          
每天10点15分触发 0 15 10 * * ?          
每天10点15分触发  0 15 10 * * ? *        
每天10点15分触发  0 15 10 * * ? 2005     
2005年每天10点15分触发 0 * 14 * * ?           
每天下午的 2点到2点59分每分触发 0 0/5 14 * * ?         
每天下午的 2点到2点59分(整点开始,每隔5分触发)  0 0/5 14,18 * * ?        
每天下午的 18点到18点59分(整点开始,每隔5分触发)0 0-5 14 * * ?            
每天下午的 2点到2点05分每分触发 0 10,44 14 ? 3 WED        
3月分每周三下午的 2点10分和2点44分触发 0 15 10 ? * MON-FRI       
从周一到周五每天上午的10点15分触发 0 15 10 15 * ?            
每月15号上午10点15分触发 0 15 10 L * ?             
每月最后一天的10点15分触发 0 15 10 ? * 6L            
每月最后一周的星期五的10点15分触发 0 15 10 ? * 6L 2002-2005  
从2002年到2005年每月最后一周的星期五的10点15分触发0 15 10 ? * 6#3每月的第三周的星期五开始触发 0 0 12 1/5 * ?            
每月的第一个中午开始每隔5天触发一次 0 11 11 11 11 ?           
每年的11月11号 11点11分触发(光棍节)

细化

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

  • 出版平台:主要是录入图书信息和图书的相关图片和附件信息
  • 图书馆平台:将出版发送过来的图书进行借阅和副本的录入
  • 发布平台和零售平台:给图书录入订购、销售、库存的数量的信息
  • 中心平台:跟前台页面进行交互(管理前台页面)

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

需求一页面效果:

定时任务1.png

定时任务2.png

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

需求二页面效果:

20161229105107006.png

20161229105224275.png

20161229105247604.png

20161229105303194.png

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

20161229105736837.png

说明:这里我单独定义一个包,来写定时任务的代码 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")  
@Controller  
public class ScheduleJobController {  
  
  
}<strong>  
</strong> 

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 
 */  
@Component  
public 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 
 */  
@DisallowConcurrentExecution  
public 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;  
        }  
  
    }  
    @Override  
    public ScheduleJobVo get(Long scheduleJobId) {  
        return schedulejobRepository.findById(scheduleJobId);  
    }  
    @Override  
    public void updateStatus(String status,Long scheduleJobId) {  
        schedulejobRepository.updateStatus(status,scheduleJobId);  
          
    }  
    @Override  
    public List<ScheduleJobVo> findByStyle(String sendStyle) {  
        return schedulejobRepository.findByStyle(sendStyle);  
    }  
    @Override  
    public void updateDesc(Long desc, Long sid) {  
        schedulejobRepository.updateStatus(desc, sid);  
          
    }  
    @Override  
    public List<ScheduleJobVo> findById(Long id) {  
        return schedulejobRepository.findBySId(id);  
    }  
    @Override  
    public void deleteBySid(Long sid) {  
        schedulejobRepository.delete_strategy(sid);  
          
    }  
    @Override  
    public 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  = "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框架。

更加细化

有时候,我们用quartz有这样的需求,在保存定时任务的表中增加一列,是一个定时任务,一个触发的时间,然后根据你设置的时间会执行定时任务。但是,当我设置多个时间的话,我不可能每次一个一个设置,一个一个保存到数据库(这里针对于页面交互型的,而不是配置文件设置的形式),这样的话太繁琐,那怎么解决呢?

我的设置界面如下:

quartz1.png

20170110110036433.png

数据库保存之后的形式

20170110110204636.png

这里可以根据设置的时间可以看出设置形式,页面交互的话转换成这种形式即可。

代码:


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;  
cron = "0 "+express+" ? *"+" "+newName;  
scheduleJobVo.setCronExpression(cron);//把设置好的expression保存到数据库

本文发表于2019年04月26日 16:00
(c)注:本文转载自https://my.oschina.net/u/3705164/blog/3042863,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。如有侵权行为,请联系我们,我们会及时删除.

阅读 1513 讨论 0 喜欢 0

抢先体验

扫码体验
趣味小程序
文字表情生成器

闪念胶囊

你要过得好哇,这样我才能恨你啊,你要是过得不好,我都不知道该恨你还是拥抱你啊。

直抵黄龙府,与诸君痛饮尔。

那时陪伴我的人啊,你们如今在何方。

不出意外的话,我们再也不会见了,祝你前程似锦。

这世界真好,吃野东西也要留出这条命来看看

快捷链接
网站地图
提交友链
Copyright © 2016 - 2021 Cion.
All Rights Reserved.
京ICP备2021004668号-1