Spring管理quartz动态创建定时器,增,删,改,查

首先最近项目中需要用到定时器,定时执行程序,snmp抓取服务器的各种状态。然后客户那边的要求是管理员可以修改定时器的执行时间。( fuck )。原本是用spring的@Scheduled注解配置 直接解决的,但是修改起来很不方便(本人太菜,是压根没法修改)。然后找了些许资料,有一篇给了启发,但是感觉他封装的还不是多好(就是没得我的牛逼),前人栽树后人乘凉,在此也感谢那篇文章和作者。我这个还是很强大的。

原文地址:http://blog.csdn.net/ynztpwl/article/details/7875191

1.首先导入quartz的jar包,xxx.jar、xxx.jar,然后再spring 容器中加入配置

<bean  class="org.springframework.scheduling.quartz.SchedulerFactoryBean"/>

2.书写自己封装的定时器类TimerEntity

public class TimerEntity {
	private String name; //名称
	private String group;//分组
	private String Description; //说明
	private String cronExpression; // 定时任务运行时间表达式
	private int status; // 任务的状态,0:启用;1:禁用
	private Class<?> statefulMethodInvokingJob;//同步的执行类,需要从StatefulMethodInvokingJob继承  
        private Class<?> methodInvokingJob;//异步的执行类,需要从MethodInvokingJob继承  
        public String getTriggerName(){
    	 return "TriggerName_"+this.getName();
        }
    /**
     * 这里重写equals方法,注意不要加入status字段的比较,等下在查询的时候有用
     */
    @Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		TimerEntity other = (TimerEntity) obj;
		if (Description == null) {
			if (other.Description != null)
				return false;
		} else if (!Description.equals(other.Description))
			return false;
		if (cronExpression == null) {
			if (other.cronExpression != null)
				return false;
		} else if (!cronExpression.equals(other.cronExpression))
			return false;
		if (group == null) {
			if (other.group != null)
				return false;
		} else if (!group.equals(other.group))
			return false;
		if (methodInvokingJob == null) {
			if (other.methodInvokingJob != null)
				return false;
		} else if (!methodInvokingJob.equals(other.methodInvokingJob))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (statefulMethodInvokingJob == null) {
			if (other.statefulMethodInvokingJob != null)
				return false;
		} else if (!statefulMethodInvokingJob
				.equals(other.statefulMethodInvokingJob))
			return false;
		return true;
	}
	public String getCronExpression() {
		return cronExpression;
	}
	public void setCronExpression(String cronExpression) {
		this.cronExpression = cronExpression;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getGroup() {
		return group;
	}
	public void setGroup(String group) {
		this.group = group;
	}
	public String getDescription() {
		return Description;
	}
	public void setDescription(String description) {
		Description = description;
	}
	public int getStatus() {
		return status;
	}
	public void setStatus(int status) {
		this.status = status;
	}
	public Class<?> getStatefulMethodInvokingJob() {
		return statefulMethodInvokingJob;
	}
	public void setStatefulMethodInvokingJob(Class<?> statefulMethodInvokingJob) {
		this.statefulMethodInvokingJob = statefulMethodInvokingJob;
	}
	public Class<?> getMethodInvokingJob() {
		return methodInvokingJob;
	}
	public void setMethodInvokingJob(Class<?> methodInvokingJob) {
		this.methodInvokingJob = methodInvokingJob;
	}
}

3.定时器管理类TimerManager(核心类)

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.quartz.CronTrigger;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.springframework.stereotype.Component;

import com.lwp.entity.TimerEntity;
@Component(value="tm")
public class TimerManager {
	@Resource
	private Scheduler scheduler;
	/**
	 * 创建或者修改
	 * @param timer
	 * @param paramsMap 参数
	 * @param isStateFull 是否是一个同步定时任务,true:同步,false:异步  
	 * true setStatefulMethodInvokingJob(xxx.class)   StatefulMethodInvokingJob
	 * false setMethodInvokingJob(xxx.class)   MethodInvokingJob
	 * 
	 * @return
	 */
	public  boolean createOrUpdateTimer(TimerEntity timer,  
            JobDataMap paramsMap, boolean isStateFull) {  
        if (timer == null) {  
            return false;  
        }  
        try {  
        	//让trigger的group 等于 jobDetail的
        	//jobDetail 和 trigger(这个可以有多个) 一对一 方便管理,操作也简单
            CronTrigger trigger = (CronTrigger) scheduler  
                    .getTrigger(timer.getTriggerName(),  
                            timer.getGroup());  
            // 如果不存在该trigger则创建一个  
            if (null == trigger) {
                JobDetail jobDetail = null;  
                if (isStateFull) {  
                    jobDetail = new JobDetail(timer.getName(),  
                            timer.getGroup(),  
                            timer.getStatefulMethodInvokingJob());  
                } else {  
                    jobDetail = new JobDetail(timer.getName(),timer.getGroup(),  
                            timer.getMethodInvokingJob());  
                } 
                jobDetail.setDescription(timer.getDescription());
                jobDetail.setJobDataMap(paramsMap);  
                trigger = new CronTrigger(timer.getTriggerName(),  
                        timer.getGroup(),  
                        timer.getCronExpression());  
                
                scheduler.scheduleJob(jobDetail, trigger);  
            } else {  
                //Trigger已存在,那么更新相应的定时设置  
                trigger.setCronExpression(timer.getCronExpression());  
                scheduler.rescheduleJob(trigger.getName(), trigger.getGroup(),  
                        trigger);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
        return true;  
    }  
	
	
	
	
	/**
	 * 得到一个job的详细信息 jobDetail对象
	 * @param timerName
	 * @param timerGroup
	 * @return
	 */
	public JobDetail getJobDetail(String timerName, String timerGroup) {  
		if(null == timerName || null == timerGroup ||
				"".equals(timerName.trim()) || "".equals(timerGroup.trim())){
			return null;
		}
        try {  
            return scheduler.getJobDetail(timerName, timerGroup);  
        } catch (SchedulerException e) {  
            e.printStackTrace();  
            return null;  
        }  
    }
	/**
	 * 得到一个job的Trigger
	 * @param timerName
	 * @param timerGroup
	 * @return
	 */
	public Trigger getJobTrigger(String timerName, String timerGroup) {  
		if(null == timerName || null == timerGroup ||
				"".equals(timerName.trim()) || "".equals(timerGroup.trim())){
			return null;
		} 
        try {  
            return scheduler.getTrigger("TriggerName_"+timerName,timerGroup);  
        } catch (SchedulerException e) {  
            e.printStackTrace();  
            return null;  
        }  
    }  
	/**
	 * 得到一个job的Trigger
	 * @param timerName
	 * @param timerGroup
	 * @return
	 */
	public Trigger getJobTrigger(TimerEntity timer) {  
		if(timer == null){
			return null;
		} 
        try {  
            return scheduler.getTrigger(timer.getTriggerName(), timer.getGroup());  
        } catch (SchedulerException e) {  
            e.printStackTrace();  
            return null;  
        }  
    }  
	
	
	/**
	 * 停止一个定时器
	 * 这里我们采用pauseTriggerGroup 方式下面才能通过getPausedTriggerGroups().iterator()获取停止了的定时器
	 * @param timerTriggerGroup
	 * @return
	 */
	public boolean pauseTimer(String timerTriggerGroup){
		try {
			scheduler.pauseTriggerGroup(timerTriggerGroup);
		} catch (SchedulerException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	/**
	 * 重新启动一个定时器(采用和上面 xxxTriggerGroup 同样方式 ,如不停止和重启不对应那么无效)
	 * @param timerTriggerGroup
	 * @return
	 */
	public boolean resumeTimer(String timerTriggerGroup){
		try {
			scheduler.resumeTriggerGroup(timerTriggerGroup);
		} catch (SchedulerException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	/**
	 * 获取全部的定时器
	 * @return
	 */
	public List<JobDetail> getAllToJobDetail(){
		List<JobDetail> list = new ArrayList<JobDetail>();
    	try {
    		
			for(String jobGroup:scheduler.getJobGroupNames()){
				for(String jobName:scheduler.getJobNames(jobGroup)){
					list.add(scheduler.getJobDetail(jobName, jobGroup));
				}
			}
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
    	return list;
	}
	/**
	 * 获取全部的定时器,此方法在 getRuningTimer() 里面调用一下,其他地方无任何意义(没法区分状态)
	 * 请使用 下面的 getAll()
	 * @return
	 */
	public List<TimerEntity> getAllToTimerEntity(){
		List<TimerEntity> list = new ArrayList<TimerEntity>();
    	try {
    		TimerEntity timer = null;
    		JobDetail job = null;
			for(String jobGroup:scheduler.getJobGroupNames()){
				for(String jobName:scheduler.getJobNames(jobGroup)){
					job = scheduler.getJobDetail(jobName, jobGroup);
					timer = new TimerEntity();
					CronTrigger trigger = (CronTrigger)getJobTrigger(jobName, jobGroup);
					timer.setCronExpression(trigger.getCronExpression());
					timer.setDescription(job.getDescription());
					timer.setName(job.getName());
					//timer.setStatus() 这里默认全部为0 原生的trigger和jobDetail没有状态
					timer.setGroup(job.getGroup());
					list.add(timer);
				}
			}
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
    	return list;
	}
	/**
	 * 获取全部
	 * @return
	 */
	public List<TimerEntity> getAll(){
		List<TimerEntity> list = getRuningTimer();
		list.addAll(getPausedTimer());
		return list;
	}
	
	/**
	 * 获取停止了的定时器
	 * @return
	 */
	public List<TimerEntity> getPausedTimer(){
		List<TimerEntity> list = new ArrayList<TimerEntity>();
		//获取Paused 停止了的trigger(触发器)
		JobDetail job = null;
		TimerEntity timer = null;
		try {
			Iterator<String> i = scheduler.getPausedTriggerGroups().iterator();
			while(i.hasNext()){
				String jobGroup = i.next();
				for(String jobName:scheduler.getJobNames(jobGroup)){
					job = scheduler.getJobDetail(jobName, jobGroup);
					timer = new TimerEntity();
					timer.setCronExpression(((CronTrigger)getJobTrigger(jobName, jobGroup)).getCronExpression());
					timer.setDescription(job.getDescription());
					timer.setName(job.getName());
					timer.setStatus(1); //设置状态为1  禁止
					timer.setGroup(job.getGroup());
					list.add(timer);
					
				}
			}
		} catch (SchedulerException e) {
			e.printStackTrace();
			return null;
		}
		return list;
	}
	/**
	 * 获取正在运行的
	 * @return
	 */
	public List<TimerEntity> getRuningTimer(){
		//先获取所有的定时器,然后再从里面删除掉被停止的,剩下的就是正在执行的
		//这里重写 实体类的equals方法,里面不要加status
		List<TimerEntity> list = getAllToTimerEntity();
		list.removeAll(getPausedTimer());
		return list;
	}
	
	
	/**
	 * 删除一个定时器,不能恢复
	 * @param jobName 名称
	 * @param jobGroup 分组
	 * @return 成功true 失败false
	 */
	public boolean deleteTimer(String timerName,String timerGroup){
		try {
			scheduler.deleteJob(timerName, timerGroup);
		} catch (SchedulerException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	/**
	 * 删除一个定时器,不能恢复
	 * @param timer  自己封装的实体类
	 * @return
	 */
	public boolean deleteTimer(TimerEntity timer){
		try {
			scheduler.deleteJob(timer.getName(), timer.getGroup());
		} catch (SchedulerException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

}


4.任务类

import java.text.SimpleDateFormat;
import java.util.Date;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean.StatefulMethodInvokingJob;
/**
 * 同步和异步执行,extends 不用的类
 * StatefulMethodInvokingJob
 * MethodInvokingJob 
 * 这个是看别人说的
 * @author Administrator
 *
 */
public class Task  extends StatefulMethodInvokingJob{
	 
//	注意这里注入不了spring里面的东西,因为我们是自己通过代码创建的,需要手动获取spring的上下文
//  参考另一篇文章:http://blog.csdn.net/lwphk/article/details/39640771
//	@Resource
//	private UserService userSerice;

	@Override
	protected void executeInternal(JobExecutionContext arg0)
			throws JobExecutionException {
		System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
		System.out.println(arg0.getJobDetail().getJobDataMap().get("msg"));
	}
}
5.测试的controller控制器

import java.util.List;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import org.quartz.JobDataMap;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.lwp.entity.TimerEntity;
import com.lwp.service.Task;
import com.lwp.service.impl.TimerManager;

@Controller
public class TestController {
	@Resource(name="tm")
	private TimerManager tm;
	
	/**
	 * 启动的时候创建定时器
	 */
	@PostConstruct
	public void start(){
		//参数
		JobDataMap jdm = new JobDataMap();
		jdm.put("msg", "you are dog fuck!");
		TimerEntity timer = new TimerEntity();
		timer.setDescription("定时执行,抓取服务器数据 111111");
		timer.setCronExpression("0/3 * * * * ?");
		timer.setStatefulMethodInvokingJob(Task.class);
		timer.setName(UUID.randomUUID().toString());
		timer.setGroup(UUID.randomUUID().toString());
		tm.createOrUpdateTimer(timer, jdm, true);
		
		TimerEntity timer2 = new TimerEntity();
		timer2.setDescription("定时执行,抓取服务器数据 22222");
		timer2.setCronExpression("0/5 * * * * ?");
		timer2.setStatefulMethodInvokingJob(Task.class);
		timer2.setName(UUID.randomUUID().toString());
		timer2.setGroup(UUID.randomUUID().toString());
		tm.createOrUpdateTimer(timer2, null, true);
		
		TimerEntity timer3 = new TimerEntity();
		timer3.setDescription("定时执行,抓取服务器数据 333333");
		timer3.setCronExpression("0/10 * * * * ?");
		timer3.setStatefulMethodInvokingJob(Task.class);
		timer3.setName(UUID.randomUUID().toString());
		timer3.setGroup(UUID.randomUUID().toString());
		tm.createOrUpdateTimer(timer3, null, true);
	}
	/**
	 * 停止一个定时器
	 */
	@RequestMapping("/stop")
	public void stop(String group){
		tm.pauseTimer(group);
	}
	/**
	 * 重启定时器
	 */
	@RequestMapping("/rerun")
	public void rerun(String group){
		//sch.resumeJob("job_1", "group_1");
		//sch.resumeTriggerGroup(group);
		tm.resumeTimer(group);
		
	}
	/**
	 * 获取所有定时器
	 * @return
	 */
	@RequestMapping("/getAll")
	@ResponseBody
	public List<TimerEntity> getAll(){
    	return tm.getAll();
	}
	/**
	 * 获取 paused 停止了的定时器
	 * @return
	 */
	@RequestMapping("/getPaused")
	@ResponseBody
	public List<TimerEntity> paused(){
		return tm.getPausedTimer();
	}
	
	/**
	 * 获取正在执行的定时器
	 * @return
	 */
	@RequestMapping("/getRuning")
	@ResponseBody
	public List<TimerEntity> runing(){
		return tm.getRuningTimer();
	}
	
	
	/**
	 * 删除一个Job 不能恢复(最好是别用)
	 */
	@RequestMapping("/del")
	public void del(String name,String group){
		tm.deleteTimer(name, group);
	}
	
}


有什么问题,大家可以加群:123091904,一起讨论(一起装逼,一起飞)

注:我是新人,性格腼腆不太爱说话。如果代码写的不好有什么得罪的地方请见谅,不要来打我!我已经被大神打过了!

你可能感兴趣的:(java,spring,quartz,管理,异步)