记录自己写的代码,肯定有不对的地方,参阅的话仅供参考。
这个用的是quartz-2.2.2.jar版本,动态设置了定时任务。
public class TaskManager {
private static TaskManager instance ;
private SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
private TaskManager(){};
public static TaskManager getInstance(){
if(instance == null) instance = new TaskManager();
return instance;
}
//添加job
public void addJob(String jobName,String serviceName,String cronExpression,Map contextMap) throws Exception{
Scheduler sched = schedFact.getScheduler();
if(!sched.isStarted()) sched.start();
JobDetail jobDetail = newJob(TaskJob.class)
.withIdentity(jobName, Scheduler.DEFAULT_GROUP)
.usingJobData("serviceName", serviceName)
.build();
for(Object key : contextMap.keySet()){
jobDetail.getJobDataMap().put(key.toString(), contextMap.get(key));
}
Trigger trigger = newTrigger()
.withIdentity(jobName+"Trigger", Scheduler.DEFAULT_GROUP)
.withSchedule(cronSchedule(cronExpression))
.forJob(jobDetail)
.build();
sched.scheduleJob(jobDetail, trigger);
}
//添加job
public void addJob(String jobName,String serviceName,String cronExpression) throws Exception{
Scheduler sched = schedFact.getScheduler();
if(!sched.isStarted()) sched.start();
JobDetail jobDetail = newJob(TaskJob.class)
.withIdentity(jobName, Scheduler.DEFAULT_GROUP)
.usingJobData("serviceName", serviceName)
.build();
Trigger trigger = newTrigger()
.withIdentity(jobName+"Trigger", Scheduler.DEFAULT_GROUP)
.withSchedule(cronSchedule(cronExpression))
.forJob(jobDetail)
.build();
sched.scheduleJob(jobDetail, trigger);
}
//移除job
public void removeJob(String jobName) throws Exception{
Scheduler sched = schedFact.getScheduler();
if(!sched.isStarted()) sched.start();
sched.unscheduleJob(triggerKey(jobName + "Trigger", Scheduler.DEFAULT_GROUP));
sched.deleteJob(jobKey(jobName, Scheduler.DEFAULT_GROUP));
}
}
下面是要执行的job,写任务的逻辑
public class TaskJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
JobDataMap dataMap = context.getJobDetail().getJobDataMap();
String serviceName = dataMap.getString("serviceName");
System.out.println(serviceName);
}
}
下面是测试
public class TaskTest {
public static void main(String[] args) throws Exception {
TaskManager mm = TaskManager.getInstance();
for(int i=0;i<5;i++){
mm.addJob("测试"+i,"服务"+i, "0/10 * * * * ?");
}
Thread.sleep(100000);
}
}
哦对,时间解析,我写了个简单的,仅供参考
public String transform(String month,String day,String week){
//month 范围 1-12 即1-12月
//day 范围1-31 即1-31日 注意特殊月份2月28天 最好1-28
//week 范围MON-SUN
String result="";
if (week==null || week.equals("")) { //week 每周一次 ,他选其他都必须为null
if (month==null || month.equals("")) {
if (day==null || day.equals("")) {
result=DAY;
}else{
result="0 0 1 "+day+" * ?";
}
}else {
result="0 0 1 "+day+" "+month+" ?";
}
}else{
result="0 0 1 ? * "+week; //每周一次
}
return result;
}