Quartz(二)在Spring中动态启动,暂定,添加,删除定时功能

动态启动,暂定,添加,删除定时功能,可传参数
Spring中使用Quartz的3种方法(MethodInvokingJobDetailFactoryBean,implements Job,extends QuartzJobBean)
以下介绍一下实现job接口的方法,通过此方法可以动态启动,暂定,添加,删除定时功能,可传参数。
所有数据全部持久化到数据表中,不再需要XML配置文件存储数据。quartz已经封装了持久化方法。数据表用的MYSQL见附件
配置quartz. properties
Java代码
#============================================================================  
# Configure Main Scheduler Properties    
#============================================================================  
   
org.quartz.scheduler.instanceName = TestScheduler  
org.quartz.scheduler.instanceId = AUTO  
   
#============================================================================  
# Configure ThreadPool    
#============================================================================  
   
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool  
org.quartz.threadPool.threadCount = 5 
org.quartz.threadPool.threadPriority = 4 
   
#============================================================================  
# Configure JobStore    
#============================================================================  
   
org.quartz.jobStore.misfireThreshold = 60000 
   
#org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore  
   
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX  
##org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.oracle.OracleDelegate  
#org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.PostgreSQLDelegate  
org.quartz.jobStore.dataSource = myDS  
org.quartz.jobStore.tablePrefix = QRTZ_  
org.quartz.jobStore.isClustered = false 
   
#============================================================================  
# Configure Datasources    
#============================================================================  
   
org.quartz.dataSource.myDS.driver = com.mysql.jdbc.Driver  
org.quartz.dataSource.myDS.URL = jdbc:mysql://localhost:3306/quartz?useUnicode=true&characterEncoding=utf8  
org.quartz.dataSource.myDS.user = root  
org.quartz.dataSource.myDS.password =   
org.quartz.dataSource.myDS.maxConnections = 5 
   
#org.quartz.dataSource.myDS.driver = org.postgresql.Driver  
#org.quartz.dataSource.myDS.URL = jdbc:postgresql:dev  
#org.quartz.dataSource.myDS.user = jhouse  
#org.quartz.dataSource.myDS.password =   
#org.quartz.dataSource.myDS.maxConnections = 5 
   
#============================================================================  
# Configure Plugins   
#============================================================================  
   
org.quartz.plugin.triggHistory.class = org.quartz.plugins.history.LoggingJobHistoryPlugin  
 
#org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.JobInitializationPlugin  
# init plugin will load jobs.xml as a classpath resource i.e. /jobs.xml if not found on file system  
#org.quartz.plugin.jobInitializer.fileName=jobs.xml  
#org.quartz.plugin.jobInitializer.overWriteExistingJobs = false 
#org.quartz.plugin.jobInitializer.failOnFileNotFound = false 

#============================================================================
# Configure Main Scheduler Properties 
#============================================================================
 
org.quartz.scheduler.instanceName = TestScheduler
org.quartz.scheduler.instanceId = AUTO
 
#============================================================================
# Configure ThreadPool 
#============================================================================
 
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 5
org.quartz.threadPool.threadPriority = 4
 
#============================================================================
# Configure JobStore 
#============================================================================
 
org.quartz.jobStore.misfireThreshold = 60000
 
#org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
 
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
##org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.oracle.OracleDelegate
#org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.PostgreSQLDelegate
org.quartz.jobStore.dataSource = myDS
org.quartz.jobStore.tablePrefix = QRTZ_
org.quartz.jobStore.isClustered = false
 
#============================================================================
# Configure Datasources 
#============================================================================
 
org.quartz.dataSource.myDS.driver = com.mysql.jdbc.Driver
org.quartz.dataSource.myDS.URL = jdbc:mysql://localhost:3306/quartz?useUnicode=true&characterEncoding=utf8
org.quartz.dataSource.myDS.user = root
org.quartz.dataSource.myDS.password =
org.quartz.dataSource.myDS.maxConnections = 5
 
#org.quartz.dataSource.myDS.driver = org.postgresql.Driver
#org.quartz.dataSource.myDS.URL = jdbc:postgresql:dev
#org.quartz.dataSource.myDS.user = jhouse
#org.quartz.dataSource.myDS.password =
#org.quartz.dataSource.myDS.maxConnections = 5
 
#============================================================================
# Configure Plugins
#============================================================================
 
org.quartz.plugin.triggHistory.class = org.quartz.plugins.history.LoggingJobHistoryPlugin

#org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.JobInitializationPlugin
# init plugin will load jobs.xml as a classpath resource i.e. /jobs.xml if not found on file system
#org.quartz.plugin.jobInitializer.fileName=jobs.xml
#org.quartz.plugin.jobInitializer.overWriteExistingJobs = false
#org.quartz.plugin.jobInitializer.failOnFileNotFound = false
在这里采用JobStoreTX,将任务持久化到数据中,而不再是简单的内存方式:RAMJobStore
在XML里加入:
在web.xml中添加QuartzInitializerServlet,Quartz为能够在web应用中使用,提供了一个QuartzInitializerServlet和一个QuartzInitializerListener,用于在加载web应用时,对quartz进行初始化。
Xml代码
<servlet> 
      <servlet-name> 
          QuartzInitializer  
      </servlet-name> 
      <servlet-class> 
          org.quartz.ee.servlet.QuartzInitializerServlet  
      </servlet-class> 
      <init-param> 
          <param-name>config-file</param-name> 
          <param-value>/quartz.properties</param-value> 
      </init-param> 
      <init-param> 
          <param-name>shutdown-on-unload</param-name> 
          <param-value>true</param-value> 
      </init-param> 
      <load-on-startup>1</load-on-startup> 
  </servlet> 

   <servlet>
         <servlet-name>
             QuartzInitializer
         </servlet-name>
         <servlet-class>
             org.quartz.ee.servlet.QuartzInitializerServlet
         </servlet-class>
         <init-param>
             <param-name>config-file</param-name>
             <param-value>/quartz.properties</param-value>
         </init-param>
         <init-param>
             <param-name>shutdown-on-unload</param-name>
             <param-value>true</param-value>
         </init-param>
         <load-on-startup>1</load-on-startup>
     </servlet>

Java代码
public interface TimerService  
{  
    public void setJobName(String jobName);  
 
    public void setJobGroup(String jobGroup);  
      
    public void setClassName(String string);  
      
    public void setCronExpression(String cronExpression);  
 
    public void setParameterNames(String[] strings);  
 
    public void setParameterValues(String[] strings);  
      
    /** 
     * 设置定时时间 
     * @param request 
     * @param jobName 
     * @param jobGroup 
     * @param triggerName 
     * @param triggerGroup 
     * @param cronExpression 
     */ 
    void saveCron(HttpServletRequest request,String jobName,String jobGroup,String triggerName,String triggerGroup,String cronExpression) throws SchedulerException, ParseException;  
      
    /** 
     * 删除定时器 
     * @param request 
     * @param jobName 
     * @param jobGroup 
     */ 
    void deleteTimer(HttpServletRequest request,String jobName,String jobGroup) throws SchedulerException;  
      
    /** 
     * 立即执行定时功能 
     * @param request 
     * @param jobName 
     * @param jobGroup 
     */ 
    void runNowTimer(HttpServletRequest request,String jobName,String jobGroup) throws SchedulerException;  
      
    /** 
     * 根据名称和组别暂停Tigger 
     * @param triggerName 
     * @param group 
     */ 
    void pauseTrigger(HttpServletRequest request,String triggerName,String group) throws SchedulerException;  
      
    /** 
     * 恢复Trigger 
     * @param triggerName 
     * @param group 
     */ 
    void resumeTrigger(HttpServletRequest request,String triggerName,String group) throws SchedulerException;  
      
    /** 
     * 删除Trigger 
     * @param triggerName 
     * @param group 
     */ 
    boolean removeTrigdger(HttpServletRequest request,String triggerName,String group) throws SchedulerException;  
}  
 
public class TimerServiceImpl implements TimerService  
{  
    private ApplicationContext appCtx = null;  
    private Scheduler scheduler;  
    private String jobName = "";  
    private String jobGroup ="";  
    private String className = "";  
    private String cronExpression = "";  
    private String parameterNames[] = {};  
    private String parameterValues[] = {};  
    private JobDetail jobDetail = new JobDetail();  
 
    public String getJobName() {  
        return jobName;  
    }  
 
    public void setJobName(String jobName) {  
        this.jobName = jobName;  
    }  
 
    public String getJobGroup() {  
        return jobGroup;  
    }  
 
    public void setJobGroup(String jobGroup) {  
        this.jobGroup = jobGroup;  
    }  
 
    public String getClassName() {  
        return className;  
    }  
 
    public void setClassName(String string) {  
        className = string.trim();  
    }  
 
    public String getCronExpression() {  
        return cronExpression;  
    }  
      
    public void setCronExpression(String cronExpression) {  
        this.cronExpression = cronExpression;  
    }  
      
    public JobDetail getJobDetail() {  
        return jobDetail;  
    }  
 
    public void setJobDetail(JobDetail detail) {  
        jobDetail = detail;  
    }  
 
    public String[] getParameterNames() {  
        return parameterNames;  
    }  
 
    public String[] getParameterValues() {  
        return parameterValues;  
    }  
 
    public void setParameterNames(String[] strings) {  
        parameterNames = strings;  
    }  
 
    public void setParameterValues(String[] strings) {  
        parameterValues = strings;  
    }  
 
    public void saveTimer(HttpServletRequest request, String[] parameterNames,String[] parameterValues,JobDetail jobDetail)   
       throws SchedulerException, ClassNotFoundException   
    {  
        className = jobDetail.getJobClass().getName();  
        Class jobClass = Class.forName(className);  
        jobDetail.setJobClass(jobClass);      
        for (int i =0; i < parameterNames.length; i++) {  
            if (parameterNames[i].trim().length() > 0 && parameterValues[i].trim().length() > 0) {  
                jobDetail.getJobDataMap().put(parameterNames[i].trim(), parameterValues[i].trim());  
                jobDetail.getJobDataMap().put(parameterNames[i].trim(), parameterValues[i].trim());  
            }  
        }  
        boolean replace = true;  
        scheduler = ScheduleBase.getCurrentScheduler(request);  
        scheduler.addJob(jobDetail, replace);  
    }  
 
    public void saveCron(HttpServletRequest request, String jobName, String jobGroup, String triggerName  
       , String triggerGroup, String cronExpression) throws SchedulerException, ParseException   
    {  
        CronTrigger trigger = null;  
        if (cronExpression.length() > 2) {  
            trigger = new CronTrigger(triggerName,triggerGroup,jobName,jobGroup,cronExpression);  
        }  
        trigger.setVolatility(false);  
        scheduler = ScheduleBase.getCurrentScheduler(request);  
        scheduler.scheduleJob(trigger);  
    }  
      
    public void deleteTimer(HttpServletRequest request, String jobName,String jobGroup) throws SchedulerException   
    {  
        this.jobDetail = scheduler.getJobDetail(jobName, jobGroup);  
        if(this.jobDetail!=null){  
            scheduler = ScheduleBase.getCurrentScheduler(request);  
            scheduler.deleteJob(jobName, "DEFAULT");  
        }  
    }  
 
    public void runNowTimer(HttpServletRequest request, String jobName,String jobGroup) throws SchedulerException   
    {  
        scheduler = ScheduleBase.getCurrentScheduler(request);  
        scheduler.triggerJob(jobName, jobGroup);  
    }  
      
    public void pauseTrigger(HttpServletRequest request, String triggerName,String group) throws SchedulerException  
    {     
        scheduler = ScheduleBase.getCurrentScheduler(request);  
        scheduler.pauseTrigger(triggerName, group);//停止触发器  
    }  
      
    public void resumeTrigger(HttpServletRequest request, String triggerName,String group) throws SchedulerException  
    {         
        scheduler = ScheduleBase.getCurrentScheduler(request);  
        //Trigger trigger = scheduler.getTrigger(triggerName, group);  
        scheduler.resumeTrigger(triggerName, group);//重启触发器  
    }  
      
    public boolean removeTrigdger(HttpServletRequest request, String triggerName,String group) throws SchedulerException  
    {         
        scheduler = ScheduleBase.getCurrentScheduler(request);  
        scheduler.pauseTrigger(triggerName, group);//停止触发器  
        return scheduler.unscheduleJob(triggerName, group);//移除触发器  
    }  
      
    public void timerDataJob(JobExecutionContext context)   
    {  
    }  
}  
//实现job接口才能定时运行  
public class TimerDataJob implements Job  
{  
 
    private ApplicationContext appCtx = null;  
    private TimerService timerService = null;  
    public void execute(JobExecutionContext context)  
            throws JobExecutionException  
    {  
        try {  
            Map parameters=context.getJobDetail().getJobDataMap();  
            String str = (String)parameters.get("");//通过此方法获得需要的参数  
            appCtx = ApplicationContextKeeper.getAppCtx();//servlet类,项目启动时讲配置文件读入  
            timerService = (TimerService)appCtx.getBean("timerService");  
            System.out.println("----------定时结束-----------");  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  

 

来源:http://mengqingyu.iteye.com/blog/568935

你可能感兴趣的:(spring,mysql,quartz,servlet,PostgreSQL)