标签:
定时任务-quartz的使用,实现可页面化管理<bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> </bean> <bean id="jobManager" class="com.temobi.quartz.JobManager"> </bean>
public class JobManager implements InitializingBean { private static final Log log = LogFactory.getLog(JobManager.class); @Autowired TaskJobService taskJobService; @Autowired QuartzManager quartzManager; @Override public void afterPropertiesSet() throws Exception { loadAllJob(); } private void loadAllJob(){ List<TaskJob> list =taskJobService.getTaskList(); quartzManager.enableCronSchedule(list); } }
@Controller public class QuartzManager { @Autowired Scheduler scheduler; private static final Log log = LogFactory.getLog(QuartzManager.class); public void enableCronSchedule(List<TaskJob> list) { for(TaskJob task : list){ SchedulingJob job = new SchedulingJob(); job.setJobId(task.getId()); job.setJobName(task.getJobName()); //job.setMemos(task.getNote()); job.setCronExpression(task.getJobCronExpression()); try{ String className= task.getJobClass().trim(); Class clazz = Class.forName(className); job.setStateFulljobExecuteClass(clazz); }catch(Exception e){ e.printStackTrace(); continue; } JobDataMap paramsMap = new JobDataMap(); paramsMap.put("jobName", task.getJobName()); if(task.getParamsKey1()!=null && task.getParamsValue1()!=null){ paramsMap.put(task.getParamsKey1(), task.getParamsValue1()); } if(task.getParamsKey2()!=null && task.getParamsValue2()!=null){ paramsMap.put(task.getParamsKey2(), task.getParamsValue2()); } if(task.getParamsKey3()!=null && task.getParamsValue3()!=null){ paramsMap.put(task.getParamsKey3(), task.getParamsValue3()); } enableCronSchedule(job, paramsMap, true); log.info("系统结束初始化任务:"+task.getId()+":"+task.getJobName()+":"+task.getJobId()); } } /** * 启动一个自定义的job * * @param schedulingJob * 自定义的job * @param paramsMap * 传递给job执行的数据 * @param isStateFull * 是否是一个同步定时任务,true:同步,false:异步 * @return 成功则返回true,否则返回false */ public boolean enableCronSchedule(SchedulingJob schedulingJob, JobDataMap paramsMap, boolean isStateFull) { if (schedulingJob == null) { return false; } try { //scheduler = (Scheduler) ApplicationHelper.getBean("scheduler"); CronTrigger trigger = (CronTrigger) scheduler.getTrigger(schedulingJob.getTriggerName(), schedulingJob.getJobGroup()); if (null == trigger) {// 如果不存在该trigger则创建一个 JobDetail jobDetail = null; if (isStateFull) { jobDetail = new JobDetail(schedulingJob.getJobId(), schedulingJob.getJobGroup(), schedulingJob.getStateFulljobExecuteClass()); } else { jobDetail = new JobDetail(schedulingJob.getJobId(), schedulingJob.getJobGroup(), schedulingJob.getJobExecuteClass()); } jobDetail.setJobDataMap(paramsMap); trigger = new CronTrigger(schedulingJob.getTriggerName(), schedulingJob.getJobGroup(), schedulingJob.getCronExpression()); scheduler.scheduleJob(jobDetail, trigger); } else { // Trigger已存在,那么更新相应的定时设置 trigger.setCronExpression(schedulingJob.getCronExpression()); scheduler.rescheduleJob(trigger.getName(), trigger.getGroup(), trigger); } } catch (Exception e) { e.printStackTrace(); return false; } return true; } /** * 禁用一个job * * @param jobId * 需要被禁用的job的ID * @param jobGroupId * 需要被警用的jobGroupId * @return 成功则返回true,否则返回false */ public boolean disableSchedule(String jobId) { if (jobId.equals("")) { return false; } try { String jobGroupId="DEFAULT"; Trigger trigger = getJobTrigger(jobId, jobGroupId); if (null != trigger) { scheduler.deleteJob(jobId, jobGroupId); } } catch (SchedulerException e) { e.printStackTrace(); return false; } return true; } /** * 得到job的详细信息 * * @param jobId * job的ID * @param jobGroupId * job的组ID * @return job的详细信息,如果job不存在则返回null */ public JobDetail getJobDetail(String jobId, String jobGroupId) { if (jobId.equals("") || jobGroupId.equals("") || null == jobId || jobGroupId == null) { return null; } try { return scheduler.getJobDetail(jobId, jobGroupId); } catch (SchedulerException e) { e.printStackTrace(); return null; } } /** * 得到job对应的Trigger * * @param jobId * job的ID * @param jobGroupId * job的组ID * @return job的Trigger,如果Trigger不存在则返回null */ public Trigger getJobTrigger(String jobId, String jobGroupId) { if (jobId.equals("") || jobGroupId.equals("") || null == jobId || jobGroupId == null) { return null; } try { return scheduler.getTrigger(jobId + "Trigger", jobGroupId); } catch (SchedulerException e) { e.printStackTrace(); return null; } } }
paramsMap.put(task.getParamsKey1(), task.getParamsValue1());这样的代码,意思是假如你:如果你在数据库的ParamsKey1值为"username",ParamsValue1的值为"zhangsang".那么你在具体的job中给定变量名为"username"的变量并给出set/get方法,就可以得到值"zhangsang",此功能适用于给定时任务配置固定参数,并且参数名字随便你定。我们这里给了三个备用的,你也可以扩展,步骤就是数据库加一个字段,在上面的程序中paramsMap放入这个字段,当然你也可以不用参数。你数据库没有配置任何值,表示该定时任务没有固定参数。
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; // 任务描述 private Class<?> stateFulljobExecuteClass;//同步的执行类,需要从StatefulMethodInvokingJob继承 private Class<?> jobExecuteClass;//异步的执行类,需要从MethodInvokingJob继承 /** * 得到该job的Trigger名字 * @return */ public String getTriggerName() { return this.getJobId() + "Trigger"; } public String getJobId() { return jobId; } public void setJobId(String jobId) { this.jobId = jobId; } public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } public String getJobGroup() { if(jobGroup==null){ jobGroup = Scheduler.DEFAULT_GROUP; } return jobGroup; } public void setJobGroup(String jobGroup) { this.jobGroup = jobGroup; } public int getJobStatus() { return jobStatus; } public void setJobStatus(int jobStatus) { this.jobStatus = jobStatus; } public String getCronExpression() { return cronExpression; } public void setCronExpression(String cronExpression) { this.cronExpression = cronExpression; } public String getMemos() { return memos; } public void setMemos(String memos) { this.memos = memos; } public Class<?> getStateFulljobExecuteClass() { return stateFulljobExecuteClass; } public void setStateFulljobExecuteClass(Class<?> stateFulljobExecuteClass) { this.stateFulljobExecuteClass = stateFulljobExecuteClass; } public Class<?> getJobExecuteClass() { return jobExecuteClass; } public void setJobExecuteClass(Class<?> jobExecuteClass) { this.jobExecuteClass = jobExecuteClass; } public static int getJS_ENABLED() { return JS_ENABLED; } public static int getJS_DISABLED() { return JS_DISABLED; } public static int getJS_DELETE() { return JS_DELETE; } }
@Controller public class ContentJob extends QuartzJobBean{ @Autowired TaskJobService taskJobService; private String beginDate; private String endDate; /** * 手动执行任务 * @param request */ @RequestMapping("/contentJobManual.do") public void manual(HttpServletRequest request) { String startDate=request.getParameter("startDate"); String endDate=request.getParameter("endDate"); TaskJobService taskJobService = (TaskJobService) ApplicationHelper.getBean("taskJobService"); Map<String, String> param = new HashMap<String, String>(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); String today=sdf.format(new Date()); if(StringUtils.isEmpty(startDate)){ param.put("beginDate", today); }else{ param.put("beginDate", startDate); } if(StringUtils.isEmpty(endDate)){ param.put("endDate", today); }else{ param.put("endDate", endDate); } taskJobService.callStatisticContent(param); } @Override public void executeInternal(JobExecutionContext context) { TaskJobService taskJobService = (TaskJobService) ApplicationHelper.getBean("taskJobService"); Map<String, String> param = new HashMap<String, String>(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); String today=sdf.format(new Date()); if(StringUtils.isEmpty(beginDate)){ param.put("beginDate", today); }else{ param.put("beginDate", beginDate); } if(StringUtils.isEmpty(endDate)){ param.put("endDate", today); }else{ param.put("endDate", endDate); } taskJobService.callStatisticContent(param); } public String getBeginDate() { return beginDate; } public void setBeginDate(String beginDate) { this.beginDate = beginDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; }
ID VARCHAR2(60) N JOB_CLASS VARCHAR2(255) N JOB_NAME VARCHAR2(60) N JOB_CRON_EXPRESSION VARCHAR2(60) N JOB_SERVICE_BEAN VARCHAR2(60) Y PARAMS_KEY1 VARCHAR2(60) Y PARAMS_VALUE1 VARCHAR2(60) Y PARAMS_KEY2 VARCHAR2(60) Y PARAMS_VALUE2 VARCHAR2(60) Y PARAMS_KEY3 VARCHAR2(60) Y PARAMS_VALUE3 VARCHAR2(60) Y NOTE VARCHAR2(255) Y JOB_STATUS VARCHAR2(1) Y UPDATETIME DATE Y JOB_AUTORUN VARCHAR2(1) Y JOB_GROUP VARCHAR2(60) Y
@Controller public class TaskJobAction{ private static final Log log = LogFactory.getLog(TaskJobAction.class); @Autowired TaskJobService taskJobService; @Autowired QuartzManager quartzManager; @RequestMapping("/enableTask.do") public void enableTask(HttpServletRequest request, HttpServletResponse response) throws IOException { String parameterStr=""; parameterStr = IOUtils.toString(request.getInputStream(), InputConstant.CHAR_SET); parameterStr = StringUtils.trim(parameterStr); parameterStr =URLDecoder.decode(parameterStr,"utf-8"); Map<String, String> p = JsonUtil.getParameterMap(parameterStr); String id=p.get("id"); if(!StringUtils.isEmpty(id)){ TaskJob task=taskJobService.getTaskById(id); List<TaskJob> list=new ArrayList<TaskJob>(); list.add(task); quartzManager.enableCronSchedule(list); task.setJobEnabled("Y"); taskJobService.update(task);//将任务设置成自动运行状态 } } @RequestMapping("/disableTask.do") public void disableTask(HttpServletRequest request, HttpServletResponse response) throws IOException { String parameterStr=""; parameterStr = IOUtils.toString(request.getInputStream(), InputConstant.CHAR_SET); parameterStr = StringUtils.trim(parameterStr); parameterStr =URLDecoder.decode(parameterStr,"utf-8"); Map<String, String> p = JsonUtil.getParameterMap(parameterStr); String id=p.get("id"); if(!StringUtils.isEmpty(id)){ TaskJob task=taskJobService.getTaskById(id); quartzManager.disableSchedule(task.getJobId()); task.setJobEnabled("N"); taskJobService.update(task);//将任务设置成非运行状态 } } @RequestMapping("/add.do") public void add(HttpServletRequest request, HttpServletResponse response) throws IOException { String parameterStr=""; parameterStr = IOUtils.toString(request.getInputStream(), InputConstant.CHAR_SET); parameterStr = StringUtils.trim(parameterStr); Map<String, String> p = JsonUtil.getParameterMap(parameterStr); String jobjson=p.get("jobjson"); jobjson=URLDecoder.decode(jobjson,"utf-8"); TaskJob task=JsonUtil.toObject(jobjson, TaskJob.class); String jobName=URLDecoder.decode(task.getJobName(),"utf-8"); task.setJobName(jobName); if(!StringUtils.isEmpty(jobjson)){ taskJobService.insert(task); } } @RequestMapping("/update.do") public void update(HttpServletRequest request, HttpServletResponse response) throws IOException { String parameterStr=""; parameterStr = IOUtils.toString(request.getInputStream(), InputConstant.CHAR_SET); parameterStr = StringUtils.trim(parameterStr); Map<String, String> p = JsonUtil.getParameterMap(parameterStr); String jobjson=p.get("jobjson"); jobjson=URLDecoder.decode(jobjson,"utf-8"); TaskJob task=JsonUtil.toObject(jobjson, TaskJob.class); String jobName=URLDecoder.decode(task.getJobName(),"utf-8"); task.setJobName(jobName); if(!StringUtils.isEmpty(jobjson)){ taskJobService.update(task); } } @RequestMapping("/delete.do") public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException { String parameterStr=""; parameterStr = IOUtils.toString(request.getInputStream(), InputConstant.CHAR_SET); parameterStr = StringUtils.trim(parameterStr); parameterStr =URLDecoder.decode(parameterStr,"utf-8"); Map<String, String> p = JsonUtil.getParameterMap(parameterStr); String idStr=p.get("idStr"); if(!StringUtils.isEmpty(idStr)){ taskJobService.delete(idStr); } } @ResponseBody @RequestMapping("/taskList.do") public RecordResultBean list(HttpServletRequest request, HttpServletResponse response,@RequestParam("pageSize") int pageSize, @RequestParam("startIndex") int startIndex) throws IOException { int pageNum=startIndex/pageSize+1; String startDate=request.getParameter("startDate"); String endDate=request.getParameter("endDate"); String jobName=request.getParameter("jobName"); if (!StringUtils.isEmpty(jobName)) { jobName=URLDecoder.decode(jobName, "UTF-8"); jobName=URLDecoder.decode(jobName, "UTF-8"); } RecordResultBean resultBean = new RecordResultBean(); try { Pager pager = new Pager(pageNum, pageSize); Map<String, Object> map = new HashMap<String, Object>(); map.put("jobName",jobName); pager.setKeys(map); pager = taskJobService.findPage(pager); if (pager == null || pager.getTotalCount() == 0) { resultBean.setResult(false); } else { resultBean.setResult(true); resultBean.setBean(pager); } }catch(Exception ex) { log.warn(JDKStackTrace.getJDKStrack(ex)); } return resultBean; }
标签:
原文地址:http://my.oschina.net/u/1757031/blog/485754