当前位置: 代码迷 >> Web前端 >> Quartz动态控制订时任务的开启与关闭以及动态配置时间规则
  详细解决方案

Quartz动态控制订时任务的开启与关闭以及动态配置时间规则

热度:125   发布时间:2013-01-26 13:47:02.0
Quartz动态控制定时任务的开启与关闭以及动态配置时间规则
为了能够实现对定时任务的动态控制,我将定时任务做了一个实体类,并将相关信息映射到了数据库中

?

package com.acca.entity;

/**
 * 
 * 任务实体
 * 
 * 
 * @author zhouhua, 2013-1-16
 */
public class SchedulingJob {

    public static final int JS_ENABLED = 0; // 任务启用状态
    public static final int JS_DISABLED = 1; // 任务禁用状态
    public static final int JS_DELETE = 2; // 任务已删除状态

    private String jobId; // 任务的Id,一般为所定义Bean的ID
    private String jobName; // 任务的描述
    private String jobGroup; // 任务所属组的名称
    private int jobStatus; // 任务的状态,0:启用;1:禁用;2:已删除
    private String cronExpression; // 定时任务运行时间表达式
    private String memos; // 任务描述

    /**
     * @return the jobId
     */
    public String getJobId() {
        return jobId;
    }

    /**
     * @param jobId the jobId to set
     */
    public void setJobId(String jobId) {
        this.jobId = jobId;
    }

    /**
     * @return the jobName
     */
    public String getJobName() {
        return jobName;
    }

    /**
     * @param jobName the jobName to set
     */
    public void setJobName(String jobName) {
        this.jobName = jobName;
    }

    /**
     * @return the jobGroup
     */
    public String getJobGroup() {
        return jobGroup;
    }

    /**
     * @param jobGroup the jobGroup to set
     */
    public void setJobGroup(String jobGroup) {
        this.jobGroup = jobGroup;
    }

    /**
     * @return the jobStatus
     */
    public int getJobStatus() {
        return jobStatus;
    }

    /**
     * @param jobStatus the jobStatus to set
     */
    public void setJobStatus(int jobStatus) {
        this.jobStatus = jobStatus;
    }

    /**
     * @return the cronExpression
     */
    public String getCronExpression() {
        return cronExpression;
    }

    /**
     * @param cronExpression the cronExpression to set
     */
    public void setCronExpression(String cronExpression) {
        this.cronExpression = cronExpression;
    }

    /**
     * @return the memos
     */
    public String getMemos() {
        return memos;
    }

    /**
     * @param memos the memos to set
     */
    public void setMemos(String memos) {
        this.memos = memos;
    }

    public String getTriggerName() {
        return this.getJobId() + "Trigger";
    }

}

?

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping >
	<class name="com.acca.entity.SchedulingJob" table="t_job"> 
		<id name="jobId">
			<generator class="uuid"/>
		</id>
		<property name="jobName"/>
		<property name="jobGroup"/>
		<property name="jobStatus"/>
		<property name="cronExpression"/>
		<property name="memos"/>
	</class>
</hibernate-mapping>

?

    /**
     * 启动定时任务
     * 
     * @param context
     * @param schedulingJob
     */
    protected void enabled(SchedulingJob schedulingJob) {
        try {
            CronTrigger trigger = (CronTrigger) this.scheduler.getTrigger(
                    schedulingJob.getTriggerName(), schedulingJob.getJobGroup());
            if (null == trigger) {
                // Trigger不存在,那么创建一个
                JobDetail jobDetail = new JobDetail(schedulingJob.getJobId(),
                        schedulingJob.getJobGroup(), QuartzJobBean.class);
                jobDetail.getJobDataMap().put("targetObjectId", schedulingJob.getJobId());

                trigger = new CronTrigger(schedulingJob.getTriggerName(),
                        schedulingJob.getJobGroup(), schedulingJob.getCronExpression());
                this.scheduler.scheduleJob(jobDetail, trigger);
            } else {
                // Trigger已存在,那么更新相应的定时设置
                trigger.setCronExpression(schedulingJob.getCronExpression());
                this.scheduler.rescheduleJob(trigger.getName(), trigger.getGroup(), trigger);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // TODO
        }
    }
这个类我放到了service层

?

    /**
     * 禁用指定的定时任务
     * 
     * @param context
     * @param schedulingJob
     */
    protected void disabled(SchedulingJob schedulingJob) {
        try {
            Trigger trigger = this.scheduler.getTrigger(schedulingJob.getTriggerName(),
                    schedulingJob.getJobGroup());
            if (null != trigger) {
                this.scheduler.deleteJob(schedulingJob.getJobId(), schedulingJob.getJobGroup());
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
            // TODO
        }
    }

?

/**
 * 
 *
 * @version sas-web v1.0
 * @author zhouhua, 2013-1-16
 */
public interface MyJob {

    public void execute();
}

?

public class QuartzJobBean implements Job {

    /**
     * @param arg0
     * @throws JobExecutionException
     * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
     */
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        String targetBeanId = (String) context.getMergedJobDataMap().get("targetObjectId");
        if (SpringUtils.isNullString(targetBeanId))
            return;
        Object targetBean = SpringUtils.getBean(targetBeanId);
        if (null == targetBean)
            return;

        // 判断是否是实现了MyJob接口
        if (!(targetBean instanceof MyJob))
            return;

        // 执行相应的任务
        ((MyJob) targetBean).execute();
    }

}

?

package com.acca.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 
 * 
 * 
 * @author zhouhua, 2013-1-16
 */
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        this.applicationContext = applicationContext;
    }

    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }
    
    /**
     * 判断字符串是否为空
     * @param str
     * @return
     */
    public static boolean isNullString(String str){
        if("".equals(str)&&str==null){
            return true;
        }else{
            return false;
        }
    }

}

?

public class QuartzJob implements MyJob {

    public void work() {
        System.out.println("Quartz的任务调度!!!"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }

    /**
     * 
     * @see com.acca.task.MyJob#execute()
     */
    @Override
    public void execute() {
        work();        
    }
}

?

public class QuartzJob01 implements MyJob {

    public void work() {
        System.out.println("Quartz01的任务调度!!!"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }

    /**
     * 
     * @see com.acca.task.MyJob#execute()
     */
    @Override
    public void execute() {
        work();        
    }
}

?

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

	<bean id="scheduler"
		class="org.springframework.scheduling.quartz.SchedulerFactoryBean" />
	<bean id="springUtils" class="com.acca.util.SpringUtils"></bean>
	<bean id="quartzJob" class="com.acca.task.QuartzJob"></bean>
	<bean id="quartzJob01" class="com.acca.task.QuartzJob01"></bean>
</beans>
这里需要注意的是:定时任务的bean id必须和数据中的id一致否则无法获取定时任务

?

public class SystemIni implements ServletContextListener {

    private JobTaskService jobTaskService;

    /**
     * @param arg0
     * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
     */
    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        // TODO Auto-generated method stub

    }

    /**
     * 项目启动时加载所有已启动的定时任务
     * 
     * @param arg0
     * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
     */
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("load....");
        ServletContext context=servletContextEvent.getServletContext();
        ApplicationContext applicationContext=WebApplicationContextUtils.getWebApplicationContext(context);
        jobTaskService=(JobTaskService) applicationContext.getBean("jobTaskService");
        jobTaskService.IniLoadClass();
    }
    

}

?

我自己写了一个demo,如果有需要的朋友可以给我邮箱,我会及时给你发过去,高手勿喷,这个demo还有一些需要改进的地方,如果高手有例子的话,还望赐教啊!!!互相交流,互相进步!!,谢谢

?

1 楼 chenxw138 前天  
呵呵,正需要,谢谢了!
邮箱:chenxw138@163.com
2 楼 FireZHFox 昨天  
chenxw138 写道
呵呵,正需要,谢谢了!
邮箱:chenxw138@163.com

已经给你发了,根据自己的需要改进吧,里面我增加了一个test页面,那个页面是用来自定义quartz的时间规则的,我的类里也写好了转换方法,你可以根据项目的要求集成到index页面中,这样给客户的体验会更好一些
  相关解决方案