项目中我们出了在spring的配置文件中配置任务调度外,有时候我们就需要手动来启动任务,停止任务。java中的任务调度的框架很多,平时用的比较多的就是quartz任务调度框架:
在编写程序过程中会涉及到版本的问题:不同版本的程序编写时不同的具体如下:
@Override
public Map<String, String> excuteXMLDataToServerTask(String excutepolicy) {
Map<String, String> map = new HashMap<String, String>();
Scheduler scheduler;
try {
scheduler = QuartzScheduleMgr.getInstanceScheduler();
if(scheduler.isStarted()){
scheduler.deleteJob("reportTask", Scheduler.DEFAULT_GROUP);
scheduler.standby();
}
CronTrigger trigger;
try {
scheduler.start();
JobDetail jobDetail = new JobDetail("reportTask", Scheduler.DEFAULT_GROUP, ClientSendToServerJob.class);
trigger = new CronTrigger("CronTrigger", null, excutepolicy);
scheduler.scheduleJob(jobDetail, trigger);
map.put("REULT", "OK");
map.put("MSG", "定时任务启动成功!");
} catch (ParseException e) {
map.put("REULT", "ERROR");
map.put("MSG", "定时任务启动失败!");
}
/*
* version 2.2.1+ JobDetail job = newJob
* (ClientSendToServerJob.class).withIdentity("job1",
* "group1").build(); Trigger trigger = newTrigger()
* .withIdentity("trigger1", "group1") .startNow()
* .withSchedule(CronScheduleBuilder.cronSchedule("0 52 0 * * ?"))
* .build();
*/
} catch (SchedulerException e) {
e.printStackTrace();
map.put("REULT", "ERROR");
map.put("MSG", "定时任务启动失败!");
}
return map;
}
//QuartzScheduleMgr schedule管理类,保证整个上下文中只有一个shcedule
package com.supermap.jointclient.util;
import java.util.Date;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
public class QuartzScheduleMgr {
private static Scheduler scheduler=getScheduler();
/**
* 创建一个调度对象
* @return
* @throws SchedulerException
*/
private static Scheduler getScheduler() {
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler scheduler=null;
try {
scheduler = sf.getScheduler();
} catch (SchedulerException e) {
e.printStackTrace();
}
return scheduler;
}
public static Scheduler getInstanceScheduler(){
return scheduler;
}
/**
* 启动一个调度对象
* @throws SchedulerException
*/
public void start() throws SchedulerException
{
scheduler.start();
}
/**
* 检查调度是否启动
* @return
* @throws SchedulerException
*/
public boolean isStarted() throws SchedulerException
{
return scheduler.isStarted();
}
/**
* 关闭调度信息
* @throws SchedulerException
*/
public void shutdown() throws SchedulerException {
scheduler.shutdown();
}
/**
* 添加调度的job信息
* @param jobdetail
* @param trigger
* @return
* @throws SchedulerException
*/
public Date scheduleJob(JobDetail jobdetail, Trigger trigger)
throws SchedulerException{
return scheduler.scheduleJob(jobdetail, trigger);
}
/**
* 添加相关的触发器
* @param trigger
* @return
* @throws SchedulerException
*/
public Date scheduleJob(Trigger trigger) throws SchedulerException{
return scheduler.scheduleJob(trigger);
}
}