最近公司要做个接口定时任务,本来考虑使用java API中的Timer + TimerTask,其实这个类还是蛮强大的,对于执行时间和执行间隔,调控起来也比较容易。
timer.schedule(new MyTask(),calendar.getTime(), 24*60*60*1000)
也就准备用着个了,写个listener监听器,启动服务器一直报null错误。因为服务器启动的时候会去执行监听器,而监听器会执行到这个schedule方法,也就是
说会去执行new MyTask(),此时不知道是Spring未加载的原因还是什么?MyTask()中声明的service方法一直为空,弄了好长时间也没解决,放弃。
第二方案准备使用spring自带的监听器
<bean id="interfaceInvokeAutoTestTask" class="*.InterfaceInvokeAutoTestTask" > </bean> <bean id="scheduledTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"> <property name="timerTask"> <ref bean="interfaceInvokeAutoTestTask"/> </property> <!-- 任务执行周期 关于一些任务的参数请参考JDK doc文档和Spring相关文档--> <property name="period"> <value>10000000</value> </property> <!-- 延时10s 执行任务 --> <property name="delay"> <value>5000000</value> </property> </bean> <!-- 启动定时器 --> <bean id="timerBean" class="org.springframework.scheduling.timer.TimerFactoryBean"> <property name="scheduledTimerTasks"> <list> <ref bean="scheduledTask" /> </list> </property> </bean>
问题1:执行时间控制起来会麻烦点;
问题2:多次执行后执行时间会有延迟,这方面参考其他文档,
ScheduledTimerTask //执行任务单线程
问题3:spring本身已经抛弃
于是考虑使用quarts,下载,导jar就不说了。
直接开始说例子1吧
public class HelloJob implements Job {
private static Logger _log = LoggerFactory.getLogger(HelloJob.class);
/**
* <p>
* Empty constructor for job initilization
* </p>
* <p>
* Quartz requires a public empty constructor so that the
* scheduler can instantiate the class whenever it needs.
* </p>
*/
public HelloJob() {
}
/**
* <p>
* Called by the <code>{@link org.quartz.Scheduler}</code> when a
* <code>{@link org.quartz.Trigger}</code> fires that is associated with
* the <code>Job</code>.
* </p>
*
* @throws JobExecutionException
* if there is an exception while executing the job.
*/
public void execute(JobExecutionContext context)
throws JobExecutionException {
// Say Hello to the World and display the date/time
_log.info("Hello World! - " + new Date());
}
}
public class SimpleExample {
public void run() throws Exception {
Logger log = LoggerFactory.getLogger(SimpleExample.class);
log.info("------- Initializing ----------------------");
// First we must get a reference to a scheduler
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler(); // 创建一任务
log.info("------- Initialization Complete -----------");
// computer a time that is on the next round minute
Date runTime = evenMinuteDate(new Date()); //java api Calendar 方法延迟一分钟
log.info("------- Scheduling Job -------------------");
// define the job and tie it to our HelloJob class
JobDetail job = newJob(HelloJob.class)
.withIdentity("job1", "group1") //withIdentity(String name, String group) ,将job关联到组中
.build();
// Trigger the job to run on the next round minute
Trigger trigger = newTrigger()
.withIdentity("trigger1", "group1")
.startAt(runTime)
.build();
/* 生成job
public JobDetail build()
{
JobDetailImpl job = new JobDetailImpl();
job.setJobClass(jobClass);
job.setDescription(description);
if(key == null)
key = new JobKey(Key.createUniqueName(null), null);
job.setKey(key);
job.setDurability(durability);
job.setRequestsRecovery(shouldRecover);
if(!jobDataMap.isEmpty())
job.setJobDataMap(jobDataMap);
return job;
}
*/
// Tell quartz to schedule the job using our trigger
sched.scheduleJob(job, trigger); //触发器执行任务组
log.info(job.getKey() + " will run at: " + runTime);
// Start up the scheduler (nothing can actually run until the
// scheduler has been started)
sched.start();
log.info("------- Started Scheduler -----------------");
// wait long enough so that the scheduler as an opportunity to
// run the job!
log.info("------- Waiting 65 seconds... -------------");
try {
// wait 65 seconds to show job
Thread.sleep(65L * 1000L);
// executing...
} catch (Exception e) {
}
// shut down the scheduler
log.info("------- Shutting Down ---------------------");
sched.shutdown(true);
log.info("------- Shutdown Complete -----------------");
}
public static void main(String[] args) throws Exception {
SimpleExample example = new SimpleExample();
example.run();
}
}
关于简单的定时任务上面的例一已经说明
下面看例2,从任务开始时间,执行次数,执行间隔来控制任务
JobDetail job = newJob(SimpleJob.class)
.withIdentity("job1", "group1")
.build();
SimpleTrigger trigger = (SimpleTrigger) newTrigger()
.withIdentity("trigger1", "group1")
.startAt(startTime)
.build(); //默认执行一次,也就无间隔
Date ft = sched.scheduleJob(job, trigger);
log.info(job.getKey() +
" will run at: " + ft +
" and repeat: " + trigger.getRepeatCount() +
" times, every " + trigger.getRepeatInterval() / 1000 + " seconds");
//group1.job1 will run at: Mon Dec 17 10:05:30 CST 2012 and repeat: 0 times, every 0 seconds
// job3 will run 11 times (run once and repeat 10 more times)
// job3 will repeat every 10 seconds
job = newJob(SimpleJob.class)
.withIdentity("job3", "group1")
.build();
trigger = newTrigger()
.withIdentity("trigger3", "group1")
.startAt(startTime)
.withSchedule(simpleSchedule()
.withIntervalInSeconds(10)
.withRepeatCount(10))
.build();
//group1.job3 will run at: Mon Dec 17 10:05:30 CST 2012 and repeat: 10 times, every 10 seconds
// the same job (job3) will be scheduled by a another trigger
// this time will only repeat twice at a 70 second interval
trigger = newTrigger()
.withIdentity("trigger3", "group2")
.startAt(startTime)
.withSchedule(simpleSchedule()
.withIntervalInSeconds(10)
.withRepeatCount(2))
.forJob(job)
.build();
//group1.job3 will [also] run at: Mon Dec 17 10:24:30 CST 2012 and repeat: 2 times, every 10 seconds
// job4 will run 6 times (run once and repeat 5 more times)
// job4 will repeat every 10 seconds
job = newJob(SimpleJob.class)
.withIdentity("job4", "group1")
.build();
trigger = newTrigger()
.withIdentity("trigger4", "group1")
.startAt(startTime)
.withSchedule(simpleSchedule()
.withIntervalInSeconds(10)
.withRepeatCount(5))
.build();
//group1.job4 will run at: Mon Dec 17 10:24:30 CST 2012 and repeat: 5 times, every 10 seconds
// job5 will run once, five minutes in the future
job = newJob(SimpleJob.class)
.withIdentity("job5", "group1")
.build();
trigger = (SimpleTrigger) newTrigger()
.withIdentity("trigger5", "group1")
.startAt(futureDate(5, IntervalUnit.MINUTE))
.build();
//group1.job5 will run at: Mon Dec 17 10:29:18 CST 2012 and repeat: 0 times, every 0 seconds
// job6 will run indefinitely, every 40 seconds
job = newJob(SimpleJob.class)
.withIdentity("job6", "group1")
.build();
trigger = newTrigger()
.withIdentity("trigger6", "group1")
.startAt(startTime)
.withSchedule(simpleSchedule()
.withIntervalInSeconds(40)
.repeatForever())
.build();
//group1.job6 will run at: Mon Dec 17 10:24:30 CST 2012 and repeat: -1 times, every 40 seconds
// jobs can also be scheduled after start() has been called...
// job7 will repeat 20 times, repeat every five minutes
job = newJob(SimpleJob.class)
.withIdentity("job7", "group1")
.build();
trigger = newTrigger()
.withIdentity("trigger7", "group1")
.startAt(startTime)
.withSchedule(simpleSchedule()
.withIntervalInMinutes(5) //5* 60000
.withRepeatCount(20))
.build();
//group1.job7 will run at: Mon Dec 17 10:24:30 CST 2012 and repeat: 20 times, every 300 seconds
// jobs can be fired directly... (rather than waiting for a trigger)
job = newJob(SimpleJob.class)
.withIdentity("job8", "group1")
.storeDurably()
.build();
sched.addJob(job, true);
log.info("'Manually' triggering job8...");
sched.triggerJob(jobKey("job8", "group1"));
//手动触发一个任务
重新触发
// jobs can be re-scheduled...
// job 7 will run immediately and repeat 10 times for every second
log.info("------- Rescheduling... --------------------");
trigger = newTrigger()
.withIdentity("trigger7", "group1")
.startAt(startTime)
.withSchedule(simpleSchedule()
.withIntervalInMinutes(5)
.withRepeatCount(20))
.build();
显示执行信息
// display some stats about the schedule that just ran
SchedulerMetaData metaData = sched.getMetaData();
log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");
//Executed 35 jobs.
接下来看例子3,执行条件表达式
// job 1 will run every 20 seconds
JobDetail job = newJob(SimpleJob.class)
.withIdentity("job1", "group1")
.build();
CronTrigger trigger = newTrigger()
.withIdentity("trigger1", "group1")
.withSchedule(cronSchedule("0/20 * * * * ?")) // 20秒执行一次 0,20,40,0---
.build();
Date ft = sched.scheduleJob(job, trigger);
log.info(job.getKey() + " has been scheduled to run at: " + ft
+ " and repeat based on expression: "
+ trigger.getCronExpression());
//group1.job1 has been scheduled to run at: Mon Dec 17 13:11:40 CST 2012 and repeat based on expression: 0/20 * * * * ?
// job 2 will run every other minute (at 15 seconds past the minute)
job = newJob(SimpleJob.class)
.withIdentity("job2", "group1")
.build();
trigger = newTrigger()
.withIdentity("trigger2", "group1")
.withSchedule(cronSchedule("15 0/2 * * * ?")) //没隔一分钟,15秒时执行一次
.build();
下面不贴代码了,将例子中所写的表达式做个说明
// job 3 will run every other minute but only between 8am and 5pm
"0 0/2 8-17 * * ?"
// job 4 will run every three minutes but only between 5pm and 11pm
0 0/3 17-23 * * ?
// job 5 will run at 10am on the 1st and 15th days of the month
0 0 10am 1,15 * ?
// job 6 will run every 30 seconds but only on Weekdays (Monday through Friday)
0,30 * * ? * MON-FRI
// job 7 will run every 30 seconds but only on Weekends (Saturday and Sunday)
0,30 * * ? * SAT,SUN
- /* 引用别人的
- --------------------------------------
- 0 0 12 * * ? 每天12点触发
- 0 15 10 ? * * 每天10点15分触发
- 0 15 10 * * ? 每天10点15分触发
- 0 15 10 * * ? * 每天10点15分触发
- 0 15 10 * * ? 2005 2005年每天10点15分触发
- 0 * 14 * * ? 每天下午的 2点到2点59分每分触发
- 0 0/5 14 * * ? 每天下午的 2点到2点59分(整点开始,每隔5分触发)
- 0 0/5 14,18 * * ? 每天下午的 2点到2点59分(整点开始,每隔5分触发) 每天下午的 18点到18点59分(整点开始,每隔5分触发)
- 0 0-5 14 * * ? 每天下午的 2点到2点05分每分触发
- 0 10,44 14 ? 3 WED 3月分每周三下午的 2点10分和2点44分触发
- 0 15 10 ? * MON-FRI 从周一到周五每天上午的10点15分触发
- 0 15 10 15 * ? 每月15号上午10点15分触发
- 0 15 10 L * ? 每月最后一天的10点15分触发
- 0 15 10 ? * 6L 每月最后一周的星期五的10点15分触发
- 0 15 10 ? * 6L 2002-2005 从2002年到2005年每月最后一周的星期五的10点15分触发
- 0 15 10 ? * 6#3 每月的第三周的星期五开始触发
- 0 0 12 1/5 * ? 每月的第一个中午开始每隔5天触发一次
- 0 11 11 11 11 ? 每年的11月11号 11点11分触发(光棍节)
- --------------------------------------
- */
Quartz Cron 表达式支持到七个域 | |||
名称 | 是否必须 | 允许值 | 特殊字符 |
秒 | 是 | 0-59 | , - * / |
分 | 是 | 0-59 | , - * / |
时 | 是 | 0-23 | , - * / |
日 | 是 | 1-31 | , - * ? / L W |
月 | 是 | 1-12 或 JAN-DEC | , - * / |
周 | 是 | 1-7 或 SUN-SAT | , - * ? / L # |
年 | 否 | 空 或 1970-2099 | , - * / |
可以看到基本结构是 秒_分_小时_日_月_[周]_[年] 后面的周和年是可选的
其次,通配符,主要的有星号(*);问号(?);减号(-);逗号(,);斜杠(/);L字母;W字母;井号(#).
- 星号:表示任意时刻
- 问号:只能在日或周字段上使用,http://blog.csdn.net/chh_jiang/article/details/4603529 这里有比较清晰的解释,简单的理解就是日期和星期是有冲突的,指定其中一个的话,另外一个是没办法指定的,比如每个月12号和每个星期二,这两个是"互斥"的,不能用日期和周来指定所有“每个是星期二的12号”这个时间。
- 减号:范围,如 1-5秒
- 逗号:列表,如 1,5,10 秒
- 斜杠:等步长序列,如3/13秒 表示 3,16,29,42,55,3,16...
- L:仅在日和周上支持,表示允许的最后一个值,注意不要让范围和列表与L连用
- W:工作日
- 井号:为给定月份指定具体的工作日实例。把“MON#2”放在周内日期字段中,表示把任务安排在当月的第二个星期一。(引用)
例4主要讲解下job中的JobDataMap
// pass initialization parameters into the job
job1.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Green");
job1.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);
public void execute(JobExecutionContext context)
throws JobExecutionException {
// This job simply prints out its job name and the
// date and time that it is running
JobKey jobKey = context.getJobDetail().getKey();
// Grab and print passed parameters
JobDataMap data = context.getJobDetail().getJobDataMap();
String favoriteColor = data.getString(FAVORITE_COLOR);
int count = data.getInt(EXECUTION_COUNT);
}
后面的例子看了看,就不介绍了。前面这些基本就够了
工作中的过程
1。页面部分,主要是一些任务的定制
页面代码
略
任务代码
/**
* 开启定时任务
* @param id
*/
private void startTaskById(String id){
//获得定时任务信息
SysInterfaceTimerTask newTask = sysInterfaceTimerTaskService.selectByTemplateID(id);
String taskId = newTask.getId(); //主键
Date startTime = newTask.getStartTime();
Date stopTime = newTask.getStopTime();
String conditionK = newTask.getConditionK();
String conditionV = newTask.getConditionV();
String tempId = newTask.getFId(); //模板ID
try {
// 获得一个计划任务
Scheduler sched = sf.getScheduler();
MyJobListener myJobListener = new MyJobListener();
sched.getListenerManager().addJobListener(myJobListener);
if(conditionK.equals("1")){
JobDetail job = JobBuilder.newJob(InterfaceInvokeAutoTestTask.class)
.withIdentity(tempId, tempId)
.build(); //定义一个job
// 将初始化参数设置近 Job 中
job.getJobDataMap().put(InterfaceInvokeAutoTestTask.TEMPLATEID, tempId); //将当前的ID赋值给Job
SimpleTrigger simpleTrigger = (SimpleTrigger) TriggerBuilder.newTrigger()
.withIdentity(tempId,tempId)
.startAt(startTime)
.build(); //定义触发器
sched.scheduleJob(job, simpleTrigger); //绑定任务
}else if(conditionK.equals("2")){
String hour = conditionV.substring(0, conditionV.indexOf(":"));
if(stopTime == null){ //每间隔 1s 执行 1次
String minute = conditionV.substring(conditionV.indexOf(":") + 1, conditionV.indexOf(";"));
String times = conditionV.substring(conditionV.indexOf(";") + 1);
JobDetail job = JobBuilder.newJob(InterfaceInvokeAutoTestTask.class)
.withIdentity(tempId, tempId)
.usingJobData(InterfaceInvokeAutoTestTask.TEMPLATEID, tempId)
.build();
SimpleTrigger simpleTrigger = (SimpleTrigger) TriggerBuilder.newTrigger()
.withIdentity(tempId, tempId)
.startAt(startTime)
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInHours(Integer.valueOf(hour))
.withIntervalInMinutes(Integer.valueOf(minute))
.withRepeatCount(Integer.valueOf(times) - 1) //重复次数 = 执行次数 - 1
).build();
sched.scheduleJob(job, simpleTrigger);
}else{ //在一定时间范围内,每隔指定时间执行一次
String minute = conditionV.substring(conditionV.indexOf(":") + 1);
JobDetail job = JobBuilder.newJob(InterfaceInvokeAutoTestTask.class)
.withIdentity(tempId, tempId)
.usingJobData(InterfaceInvokeAutoTestTask.TEMPLATEID, tempId)
.build();
SimpleTrigger simpleTrigger = (SimpleTrigger) TriggerBuilder.newTrigger()
.withIdentity(tempId, tempId)
.startAt(startTime)
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInHours(Integer.valueOf(hour))
.withIntervalInMinutes(Integer.valueOf(minute))
.repeatForever()
)
.endAt(stopTime)
.build();
sched.scheduleJob(job, simpleTrigger);
}
}else if(conditionK.equals("3")){
JobDetail job = JobBuilder.newJob(InterfaceInvokeAutoTestTask.class)
.withIdentity(tempId, tempId)
.usingJobData(InterfaceInvokeAutoTestTask.TEMPLATEID, tempId)
.build();
SimpleTrigger simpleTrigger = (SimpleTrigger) TriggerBuilder.newTrigger()
.withIdentity(taskId, taskId)
.startAt(startTime)
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInHours(24 * Integer.valueOf(conditionV))
.repeatForever()
)
.endAt(stopTime)
.build();
sched.scheduleJob(job, simpleTrigger);
}else if(conditionK.equals("4")){
StringBuffer sb = new StringBuffer();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss"); //截取时分秒
String formatDate = simpleDateFormat.format(startTime);
String s = formatDate.substring(formatDate.lastIndexOf(":")+1);
String m = formatDate.substring(formatDate.indexOf(":")+1,formatDate.lastIndexOf(":"));
String h = formatDate.substring(0, formatDate.indexOf(":"));
sb.append(s).append(" ").append(m).append(" ").append(h).append(" ")
.append("? * ");
/*周一 Mon
周二 Tue
周三 Wed
周四 Thu
周五 Fri
周六 Sat
周日 Sun*/
String replaceWeek = conditionV.replace("AA", "Mon")
.replace("BB", "Tue")
.replace("CC", "Wed")
.replace("DD", "Thu")
.replace("EE", "Fri")
.replace("FF", "Sat")
.replace("GG", "Sun")
.replace(" ", "");
replaceWeek = replaceWeek.substring(replaceWeek.indexOf("[")+1, replaceWeek.indexOf("]"));
sb.append(replaceWeek);
JobDetail job = JobBuilder.newJob(InterfaceInvokeAutoTestTask.class)
.withIdentity(tempId, tempId)
.usingJobData(InterfaceInvokeAutoTestTask.TEMPLATEID, taskId)
.build();
CronTrigger trigger = TriggerBuilder.newTrigger()
.withIdentity(taskId, taskId)
.startAt(startTime)
.withSchedule(CronScheduleBuilder.cronSchedule(sb.toString()))
.endAt(stopTime)
.build();
sched.scheduleJob(job, trigger);
}
sched.start(); //开启定时任务
newTask.setIsRun("1");
sysInterfaceTimerTaskService.update(newTask); //任务启用后,将任务标志inRun设置为1
} catch (SchedulerException e) {
e.printStackTrace();
}
}
/**
* 停止 单个 任务
* @return
*/
public String stopTask(){
Scheduler sched = null;
try {
sched = sf.getScheduler();
SysInterfaceTimerTask delTask = sysInterfaceTimerTaskService.selectByTemplateID(sysInterfaceTemplate.getId());
sched.deleteJob(new JobKey(delTask.getFId(),delTask.getFId())); //停止任务
delTask.setIsRun("0");
sysInterfaceTimerTaskService.update(delTask); //任务停止后,将任务标志inRun设置为0
} catch (SchedulerException e) {
e.printStackTrace();
}
return "templist_redo";
}
执行任务
package com.besttone.mobile.mcipm.util.interfaceTask;
import *
/**
* 定时任务
* @author Administrator
*
*/
public class InterfaceInvokeAutoTestTask implements Job{
private SysInterfaceTemplateService sysInterfaceTemplateService = (SysInterfaceTemplateService) SpringContextUtil.getBean("sysInterfaceTemplateService");
private SysInterfaceParamsMapper sysInterfaceParamsMapper = (SysInterfaceParamsMapper) SpringContextUtil.getBean("sysInterfaceParamsMapper");
private SysInterfaceTimerInvokeMapper sysInterfaceTimerInvokeMapper = (SysInterfaceTimerInvokeMapper) SpringContextUtil.getBean("sysInterfaceTimerInvokeMapper");
private Date date; //任务开始时间
private long beginTimeInMillis; //任务开始时间
private long endTimeInMillis; //任务结束时间
//模板ID通过job.getJobDataMap() 设置
public static final String TEMPLATEID = "templateId";
/**
* 执行任务
*/
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
synchronized (InterfaceInvokeAutoTestTask.class) {
System.out.println("======================================================");
date = new Date();
beginTimeInMillis = Calendar.getInstance().getTimeInMillis(); //记录任务的开始时间
// Grab and print passed parameters
JobDataMap data = context.getJobDetail().getJobDataMap();
String templateId = data.getString(TEMPLATEID);
SysInterfaceTemplate selectByPrimaryKey = sysInterfaceTemplateService
.selectByPrimaryKey(templateId);
generateURL(selectByPrimaryKey); //返回结果信息
}
}
/**
*
* @param sysInterfaceTemplate
* @return 请求URL
*/
private void generateURL(SysInterfaceTemplate sysInterfaceTemplate){
String id = sysInterfaceTemplate.getId();
String templatename = sysInterfaceTemplate.getTemplatename();
String url = sysInterfaceTemplate.getUrl();
int paramnum = sysInterfaceTemplate.getParamnum().intValue();
String method = sysInterfaceTemplate.getMethod();
List<SysInterfaceParams> selectByTemplateId = sysInterfaceParamsMapper.selectByTemplateId(id);
List<NameValuePair> nameValueLists = new ArrayList<NameValuePair>();
StringBuffer sb = new StringBuffer(); //请求地址 类似method:*&req={k1:v1}
String keyIsInReq = "";
for(int i=0;i<paramnum;i++){
String keyString = selectByTemplateId.get(i).getParamkey();
String valueString = selectByTemplateId.get(i).getParamvalue();
String isleaf = selectByTemplateId.get(i).getIsleaf();
int sortcount = selectByTemplateId.get(i).getSortcount().intValue();
if(keyString.equals("method")){
sb.append(keyString).append("=").append(valueString);
nameValueLists.add(new NameValuePair(keyString, valueString));
}else if(isleaf.equals("1")){ //如果是非叶子节点,拼接字符串
if (valueString.indexOf("$") != -1) { //req的value 一般类似 3$4$5
String parseJSON = parseJSON(valueString, selectByTemplateId);
sb.append("&").append(keyString).append("=").append(parseJSON);
keyIsInReq = valueString;
nameValueLists.add(new NameValuePair(keyString, parseJSON));
}
}else{
if (!keyIsInReq.contains(String.valueOf(sortcount))) {
sb.append("&").append(keyString).append("=").append(valueString);
nameValueLists.add(new NameValuePair(keyString, valueString));
}
}
/*if (keyString.equalsIgnoreCase("method")) {
sb.append(keyString).append("=").append(valueString);
nameValueLists.add(new NameValuePair(keyString, valueString));
}else if(keyString.equalsIgnoreCase("req")){
sb.append("&").append(keyString).append("=");
String parseJSON = null;
if (valueString.indexOf("$") != -1) { //req的value 一般类似 3$4$5
parseJSON = parseJSON(valueString, selectByTemplateId);
// int lastIndexOf = parseJSON.lastIndexOf("}");
// if(parseJSON.substring(lastIndexOf - 2, lastIndexOf - 1).equals(",") ){
// }
sb.append(parseJSON);
}else{
sb.append(valueString);
}
nameValueLists.add(new NameValuePair(keyString, parseJSON));
}else{
//如果req中包含了当前key,则跳过,否则拼接到字符串中
if(!valueString.contains(String.valueOf((i+1)))){
sb.append("&").append(keyString).append("=").append(valueString);
nameValueLists.add(new NameValuePair(keyString, valueString));
}
}*/
}
try {
String sendRequest = sendRequest(nameValueLists, method, url, sb.toString());
SysInterfaceTimerInvoke sysInterfaceTimerInvoke = new SysInterfaceTimerInvoke();
sysInterfaceTimerInvoke.setTemplateName(templatename);
sysInterfaceTimerInvoke.setUrl(url);
sysInterfaceTimerInvoke.setMethod(method);
sysInterfaceTimerInvoke.setParamNum(paramnum);
sysInterfaceTimerInvoke.setParam(sb.toString());
sysInterfaceTimerInvoke.setStartTime(date);
if (sendRequest.substring(0, 9).equals("Exception")) {
sysInterfaceTimerInvoke.setResult("失败");
}else{
if(sendRequest.indexOf("\"result\":\"00\"") > -1){
sysInterfaceTimerInvoke.setResult("成功");
}else {
sysInterfaceTimerInvoke.setResult("失败");
}
}
sysInterfaceTimerInvoke.setMessage(sendRequest);
endTimeInMillis = Calendar.getInstance().getTimeInMillis(); //记录任务的结束时间
long invokeTime = endTimeInMillis - beginTimeInMillis;
sysInterfaceTimerInvoke.setInvokeTime(invokeTime+" ms");
sysInterfaceTimerInvokeMapper.insert(sysInterfaceTimerInvoke);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String parseJSON(String valueString , List<SysInterfaceParams> selectByTemplateId){
// JSON表达式,类似于 3&4&5
String[] json = valueString.split("\\$");
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("{");
for (String n : json) {
String paramkey = selectByTemplateId.get(Integer.parseInt(n)-1).getParamkey();
String paramvalue = selectByTemplateId.get(Integer.parseInt(n)-1).getParamvalue();
// if(paramvalue.indexOf("\\$") > 0 ){
// parseJSON(paramvalue,selectByTemplateId);
// } //用不到啦
stringBuffer.append("\""
+ paramkey
+ "\"" + ":" + "\""
+ paramvalue
+ "\"");
stringBuffer.append(",");
}
stringBuffer.deleteCharAt(stringBuffer.length() - 1);
stringBuffer.append("}");
return stringBuffer.toString();
}
/**
* 发送请求
* @return
* @throws IOException
* @throws HttpException
*/
public String sendRequest(List<NameValuePair> lists, String type, String url, String params) throws HttpException, IOException{
String responseBodyAsString ;
GetMethod getMethod = null;
PostMethod postMethod = null;
try {
if(type.equalsIgnoreCase("get")){
if (params.trim().equals("")) {
getMethod = new GetMethod(url);
} else {
getMethod = new GetMethod(url + "?" + params);
}
HttpClient httpClient = new HttpClient();
httpClient.executeMethod(getMethod);
responseBodyAsString = getMethod.getResponseBodyAsString();
getMethod.releaseConnection();
}else{
postMethod = new GBKPostMethod(url);
NameValuePair[] data = new NameValuePair[lists.size()];
for (int i = 0; i < lists.size(); i++) {
data[i] = lists.get(i);
}
postMethod.setRequestBody(data);
HttpClient httpClient = new HttpClient();
httpClient.executeMethod(postMethod);
responseBodyAsString = postMethod.getResponseBodyAsString();
postMethod.releaseConnection();
}
} catch (Exception e) {
e.printStackTrace();
responseBodyAsString = "Exception :"+e.getMessage();
return responseBodyAsString;
} finally{
if (getMethod != null) {
getMethod.releaseConnection();
}
if(postMethod != null){
postMethod.releaseConnection();
}
}
return responseBodyAsString;
}
}
任务监听接口
package com.besttone.mobile.mcipm.util.interfaceTask;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import com.besttone.mobile.mcipm.dao.SysInterfaceTimerTaskMapper;
import com.besttone.mobile.mcipm.model.SysInterfaceTimerTask;
import com.besttone.mobile.mcipm.util.SpringContextUtil;
public class MyJobListener implements JobListener {
private SysInterfaceTimerTaskMapper sysInterfaceTimerTaskMapper = (SysInterfaceTimerTaskMapper) SpringContextUtil.getBean("sysInterfaceTimerTaskMapper");
@Override
public String getName() {
return "myJobListenerName";
}
@Override
public void jobExecutionVetoed(JobExecutionContext arg0) {
}
@Override
public void jobToBeExecuted(JobExecutionContext context) {
System.out.println("任务开始进行了");
}
@Override
public void jobWasExecuted(JobExecutionContext context,
JobExecutionException arg1) {
JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
Map<String, Object> wrappedMap = jobDataMap.getWrappedMap();
Collection<Object> values = wrappedMap.values();
String templateId = null;
for (Object object : values) {
templateId = (String)object; //获得当前任务的ID号
}
try {
/* 设置为 一个触发器触发一个任务
* 获得当前触发器的下一次执行时间,如果为null的话
* 则表示当前的任务已经执行完
*/
Date nextFireTime = context.getScheduler().getTrigger(new TriggerKey(templateId,templateId)).getNextFireTime();
//当任务的下一次执行时间为null的时候,表示任务已经结束了,此时将任务的运行状态设置为停止 (0)
if(nextFireTime == null){
SysInterfaceTimerTask selectByTemplateID = sysInterfaceTimerTaskMapper.selectByTemplateID(templateId);
selectByTemplateID.setIsRun("0");
sysInterfaceTimerTaskMapper.updateByTempId(selectByTemplateID);
}
} catch (SchedulerException e) {
e.printStackTrace();
}
System.out.println("任务执行完成了");
}
}
至此,计划任务基本完成。