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";
    }

}

 




	 
		
			
		
		
		
		
		
		
	

 

    /**
     * 启动定时任务
     * 
     * @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();        
    }
}

 




	
	
	
	

这里需要注意的是:定时任务的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还有一些需要改进的地方,如果高手有例子的话,还望赐教啊!!!互相交流,互相进步!!,谢谢

 

你可能感兴趣的:(spring,easyUI)