标签:
-- Create table Oracle数据库
create table QUARTZ_SCHEDULEJOB
(
id VARCHAR2(32),
job_name VARCHAR2(32) not null,
job_status NVARCHAR2(3) default 0 not null,
cron_expression NVARCHAR2(32) not null,
concurrent NVARCHAR2(3) default 0,
description NVARCHAR2(320),
job_group NVARCHAR2(32),
target_object NVARCHAR2(32),
target_method NVARCHAR2(32),
is_spring_bean NVARCHAR2(3),
clazz NVARCHAR2(80),
child_jobs NVARCHAR2(302)
)
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
-- Add comments to the columns
comment on column QUARTZ_SCHEDULEJOB.id
is ‘任务id‘;
comment on column QUARTZ_SCHEDULEJOB.job_name
is ‘任务名称‘;
comment on column QUARTZ_SCHEDULEJOB.job_status
is ‘任务状态 0禁用 1启用‘;
comment on column QUARTZ_SCHEDULEJOB.cron_expression
is ‘任务运行时间表达式‘;
comment on column QUARTZ_SCHEDULEJOB.concurrent
is ‘是否并发启动任务 0禁用 1启用‘;
comment on column QUARTZ_SCHEDULEJOB.description
is ‘任务描述‘;
comment on column QUARTZ_SCHEDULEJOB.job_group
is ‘任务所属组‘;
comment on column QUARTZ_SCHEDULEJOB.target_object
is ‘执行任务的类‘;
comment on column QUARTZ_SCHEDULEJOB.target_method
is ‘任务类中的方法‘;
comment on column QUARTZ_SCHEDULEJOB.is_spring_bean
is ‘是否是Spring中定义的Bean 0不是 1是 如果是0需要设置全类名,测试CLAZZ字段需要配置‘;
comment on column QUARTZ_SCHEDULEJOB.clazz
is ‘如果不是Spring中的Bean需要配置全类名用于反射‘;
comment on column QUARTZ_SCHEDULEJOB.child_jobs
is ‘[一系列(包括单个)]的子任务(按照配置的顺序执行)‘;
insert into QUARTZ_SCHEDULEJOB (id, job_name, job_status, cron_expression, concurrent, description, job_group, target_object, target_method, is_spring_bean, clazz, child_jobs)
values (‘01‘, ‘car_starting‘, ‘0‘, ‘0/5 * * * * ?‘, ‘0‘, ‘车辆启动‘, ‘car‘, ‘car‘, ‘starting‘, ‘1‘, null, ‘03,02‘);
insert into QUARTZ_SCHEDULEJOB (id, job_name, job_status, cron_expression, concurrent, description, job_group, target_object, target_method, is_spring_bean, clazz, child_jobs)
values (‘02‘, ‘car_running‘, ‘1‘, ‘0/30 * * * * ?‘, ‘0‘, ‘车辆开动‘, ‘car‘, ‘car‘, ‘running‘, ‘1‘, null, ‘06,05‘);
insert into QUARTZ_SCHEDULEJOB (id, job_name, job_status, cron_expression, concurrent, description, job_group, target_object, target_method, is_spring_bean, clazz, child_jobs)
values (‘03‘, ‘car_stop‘, ‘0‘, ‘0/3 * * * * ?‘, ‘0‘, ‘车辆停止‘, ‘car‘, ‘car‘, ‘stop‘, ‘1‘, null, null);
insert into QUARTZ_SCHEDULEJOB (id, job_name, job_status, cron_expression, concurrent, description, job_group, target_object, target_method, is_spring_bean, clazz, child_jobs)
values (‘04‘, ‘people_birth‘, ‘0‘, ‘0/6 * * * * ?‘, ‘0‘, ‘人出生‘, ‘people‘, ‘people‘, ‘birth‘, ‘1‘, null, ‘01‘);
insert into QUARTZ_SCHEDULEJOB (id, job_name, job_status, cron_expression, concurrent, description, job_group, target_object, target_method, is_spring_bean, clazz, child_jobs)
values (‘05‘, ‘people_life‘, ‘0‘, ‘0/3 * * * * ?‘, ‘0‘, ‘人生活‘, ‘people‘, ‘people‘, ‘life‘, ‘1‘, null, null);
insert into QUARTZ_SCHEDULEJOB (id, job_name, job_status, cron_expression, concurrent, description, job_group, target_object, target_method, is_spring_bean, clazz, child_jobs)
values (‘06‘, ‘people_death‘, ‘0‘, ‘0/4 * * * * ?‘, ‘0‘, ‘人死亡‘, ‘people‘, ‘people‘, ‘death‘, ‘1‘, null, null);
insert into QUARTZ_SCHEDULEJOB (id, job_name, job_status, cron_expression, concurrent, description, job_group, target_object, target_method, is_spring_bean, clazz, child_jobs)
values (‘07‘, ‘out‘, ‘0‘, ‘0/4 * * * * ?‘, ‘0‘, ‘outout‘, ‘outout‘, ‘testreflectionClazz‘, ‘testreflectionClazz‘, ‘0‘, ‘com.cn.model.TestreflectionClazz‘, null);
package com.cn.model;
import java.io.Serializable;
/**
* 计划任务信息
* @author 杨润康
*/
public class ScheduleJob implements Serializable{
private static final long serialVersionUID = -6268330198581041868L;
/** 任务ID */
private String jobId;
/** 任务名称 */
private String jobName;
/** 任务分组 */
private String jobGroup;
/** 任务状态 0禁用 1启用 2删除*/
private String jobStatus;
/** 任务运行时间表达式 */
private String cronExpression;
/** 任务描述 */
private String description;
/** 任务类 */
private String targetObject;
/** 任务方法 */
private String targetMethod;
/** 是否是Spring中定义的Bean */
private String isSpringBean;
/** 如果isSpringBean = 0需要设置全类名,测试CLAZZ字段需要配置 */
private String clazz;
/** 是否并发 0禁用 1启用 */
private String concurrent;
/** 一系列的子任务,逗号分开,表示该任务执行完,之后需要执行的任务 */
private String childJobs;
public String getChildJobs() {
return childJobs;
}
public void setChildJobs(String childJobs) {
this.childJobs = childJobs;
}
public String getConcurrent() {
return concurrent;
}
public void setConcurrent(String concurrent) {
this.concurrent = concurrent;
}
public String getClazz() {
return clazz;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
public String getIsSpringBean() {
return isSpringBean;
}
public void setIsSpringBean(String isSpringBean) {
this.isSpringBean = isSpringBean;
}
public String getTargetObject() {
return targetObject;
}
public void setTargetObject(String targetObject) {
this.targetObject = targetObject;
}
public String getTargetMethod() {
return targetMethod;
}
public void setTargetMethod(String targetMethod) {
this.targetMethod = targetMethod;
}
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() {
return jobGroup;
}
public void setJobGroup(String jobGroup) {
this.jobGroup = jobGroup;
}
public String getJobStatus() {
return jobStatus;
}
public void setJobStatus(String jobStatus) {
this.jobStatus = jobStatus;
}
public String getCronExpression() {
return cronExpression;
}
public void setCronExpression(String cronExpression) {
this.cronExpression = cronExpression;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "ScheduleJob [jobId=" + jobId + ", jobName=" + jobName + ", jobGroup=" + jobGroup + ", jobStatus="
+ jobStatus + ", cronExpression=" + cronExpression + ", description=" + description + ", targetObject="
+ targetObject + ", targetMethod=" + targetMethod + ", isSpringBean=" + isSpringBean + ", clazz="
+ clazz + ", concurrent=" + concurrent + ", childJobs=" + childJobs + "]";
}
}
- com.cn.model.TestreflectionClazz
package com.cn.model;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.log4j.Logger;
/**
* 测试不是Spring中的Bean 测试isSpringBean为0 的情况
* @author 杨润康
* 测试OK
*/
public class TestreflectionClazz {
private Logger logger = Logger.getLogger(TestreflectionClazz.class);
private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public void testreflectionClazz(){
logger.info(df.format(new Date()) + "------------>TestreflectionClazz");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void task1_test1_test2(){
}
}
- com.cn.quartz.inputs.QuartzJobFactory
package com.cn.quartz.inputs;
import java.util.List;
import org.apache.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import com.cn.model.ScheduleJob;
import com.cn.util.DBUtil;
import com.cn.util.QuartzUtil;
import com.cn.util.SpringContextUtil;
/**
* 定时任务运行工厂类
*
* @author 杨润康
*/
@DisallowConcurrentExecution
public class QuartzJobFactory {// 实现的是无状态的Job
private Logger logger = Logger.getLogger(QuartzJobFactory.class);
/**
* @Note : 扫面数据库,查看是否有计划任务的变动
*/
public void arrageScheduleJob() {
try {
List<ScheduleJob> jobList = DBUtil.getScheduleJobs();
if (jobList.size() != 0) {
for (ScheduleJob job : jobList) {
// Keys are composed of both a name and group, and the name must be unique within the group
TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());
// 获取trigger
CronTrigger trigger = (CronTrigger) QuartzUtil.scheduler.getTrigger(triggerKey);
// 不存在,创建一个
if (null == trigger) {
createSheduler(QuartzUtil.scheduler, job);
} else {// Trigger已存在,那么更新相应的定时设置
updateScheduler(QuartzUtil.scheduler, job, triggerKey, trigger);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 更新相应的定时设置 根据job_status做相应的处理
*
* @param scheduler
* @param job
* @param triggerKey
* @param trigger
* @throws SchedulerException
*/
private void updateScheduler(Scheduler scheduler, ScheduleJob job, TriggerKey triggerKey, CronTrigger trigger)
throws SchedulerException {
if (job.getJobStatus().equals("1")) {// 0禁用 1启用
if (!trigger.getCronExpression().equalsIgnoreCase(job.getCronExpression())) {
// 表达式调度构建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
// 按新的cronExpression表达式重新构建trigger
trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
// 按新的trigger重新设置job执行
scheduler.rescheduleJob(triggerKey, trigger);
logger.info(job.getJobGroup() + "." + job.getJobName() + " 更新完毕,目前cron表达式为:" + job.getCronExpression()
+ " isSpringBean:" + job.getIsSpringBean() + " concurrent: " + job.getConcurrent());
}
} else if (job.getJobStatus().equals("0")) {
scheduler.pauseTrigger(triggerKey);// 停止触发器
scheduler.unscheduleJob(triggerKey);// 移除触发器
scheduler.deleteJob(trigger.getJobKey());// 删除任务
logger.info(job.getJobGroup() + "." + job.getJobName() + "删除完毕");
}
}
/**
* 创建一个定时任务,并做安排
*
* @param scheduler
* @param job
* @throws SchedulerException
* @throws Exception
*/
public void createSheduler(Scheduler scheduler, ScheduleJob job) throws Exception {
// 在工作状态可用时,即job_status = 1 ,开始创建
if (job.getJobStatus().equals("1")) {
// 新建一个基于Spring的管理Job类
MethodInvokingJobDetailFactoryBean methodInvJobDetailFB = new MethodInvokingJobDetailFactoryBean();
// 设置Job名称
methodInvJobDetailFB.setName(job.getJobName());
// 定义的任务类为Spring的定义的Bean则调用 getBean方法
if (job.getIsSpringBean().equals("1")) {// 是Spring中定义的Bean
methodInvJobDetailFB
.setTargetObject(SpringContextUtil.getApplicationContext().getBean(job.getTargetObject()));
} else {// 不是
methodInvJobDetailFB.setTargetObject(Class.forName(job.getClazz()).newInstance());
}
// 设置任务方法
methodInvJobDetailFB.setTargetMethod(job.getTargetMethod());
// 将管理Job类提交到计划管理类
methodInvJobDetailFB.afterPropertiesSet();
/** 并发设置 */
methodInvJobDetailFB.setConcurrent(job.getConcurrent().equals("1") ? true : false);
JobDetail jobDetail = methodInvJobDetailFB.getObject();// 动态
jobDetail.getJobDataMap().put("scheduleJob", job);
//jobName存入到队列 每隔一段时间就会扫描所以需要时检测
if(!QuartzUtil.jobNames.contains(job.getJobName())){
QuartzUtil.jobNames.add(job.getJobName());
}
// 表达式调度构建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
// 按新的cronExpression表达式构建一个新的trigger
CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(), job.getJobGroup())
.withSchedule(scheduleBuilder).build();
scheduler.scheduleJob(jobDetail, trigger);// 注入到管理类
logger.info(job.getJobGroup() + "." + job.getJobName() + "创建完毕");
}
}
}
- com.cn.tasks.Car
package com.cn.tasks;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cn.util.QuartzUtil;
@Component
public class Car {
private Logger logger = Logger.getLogger(Car.class);
private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public void starting() {
logger.info(df.format(new Date()) + "---------->车辆启动");
String mainJob = QuartzUtil.getScheduleJobName("car_starting");
QuartzUtil.executeChildJobs(mainJob);
}
public void running() {
logger.info(df.format(new Date()) + "---------->车辆开动");
String mainJob = QuartzUtil.getScheduleJobName("car_running");
QuartzUtil.executeChildJobs(mainJob);
}
public void stop() {
logger.info(df.format(new Date()) + "---------->车辆停止");
String mainJob = QuartzUtil.getScheduleJobName("car_stop");
QuartzUtil.executeChildJobs(mainJob);
}
}
- com.cn.tasks.People
package com.cn.tasks;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cn.util.QuartzUtil;
import com.cn.util.Util;
@Component
public class People {
private Logger logger = Logger.getLogger(Car.class);
private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public synchronized void birth(){
// logger.info("人出生耗时操作10s");
// Util.time_10s();
logger.info(df.format(new Date()) + "---------->人出生");
String mainJob = QuartzUtil.getScheduleJobName("people_birth");
QuartzUtil.executeChildJobs(mainJob);
}
public synchronized void life(){
// logger.info("人生活耗时操作8s");
// Util.time_8s();
logger.info(df.format(new Date()) + "---------->人生活");
String mainJob = QuartzUtil.getScheduleJobName("people_life");
QuartzUtil.executeChildJobs(mainJob);
}
public synchronized void death(){
// logger.info("人死亡耗时操作6s");
// Util.time_6s();
logger.info(df.format(new Date()) + "---------->人死亡");
String mainJob = QuartzUtil.getScheduleJobName("people_death");
QuartzUtil.executeChildJobs(mainJob);
}
}
- com.cn.util.DBUtil
package com.cn.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import com.cn.model.ScheduleJob;
/**
* 数据库工具类
*
* @author 杨润康Bla
*
*/
public class DBUtil {
/**
* 查询数据库任务设置,返回列表
*
* @return 数据库任务设置列表
*/
public static List<ScheduleJob> getScheduleJobs() {
List<ScheduleJob> result = new ArrayList<ScheduleJob>();
Connection con = null;
Statement smt = null;
ResultSet rs = null;
con = new DBUtil().getDBConnection();
try {
if (con != null) {
smt = con.createStatement();
con.setAutoCommit(false);
String sql = "SELECT ID,JOB_NAME,JOB_STATUS,CRON_EXPRESSION,CONCURRENT,DESCRIPTION,JOB_GROUP,TARGET_OBJECT,TARGET_METHOD,IS_SPRING_BEAN,CLAZZ,CHILD_JOBS FROM QUARTZ_SCHEDULEJOB";
rs = smt.executeQuery(sql);
while (rs.next()) {
ScheduleJob sj = new ScheduleJob();
sj.setJobId(rs.getString("ID"));
sj.setJobName(rs.getString("JOB_NAME"));
sj.setJobGroup(rs.getString("JOB_GROUP"));
sj.setJobStatus(rs.getString("JOB_STATUS"));
sj.setCronExpression(rs.getString("CRON_EXPRESSION"));
sj.setDescription(rs.getString("DESCRIPTION"));
sj.setTargetMethod(rs.getString("TARGET_METHOD"));
sj.setTargetObject(rs.getString("TARGET_OBJECT"));
sj.setIsSpringBean(rs.getString("IS_SPRING_BEAN"));
sj.setClazz(rs.getString("CLAZZ"));
sj.setConcurrent(rs.getString("CONCURRENT"));
sj.setChildJobs(rs.getString("CHILD_JOBS"));
result.add(sj);
}
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
public static ScheduleJob getScheduleJobById(String id) {
Connection con = null;
Statement smt = null;
ResultSet rs = null;
ScheduleJob sj = null;
con = new DBUtil().getDBConnection();
try {
if (con != null) {
smt = con.createStatement();
con.setAutoCommit(false);
String sql = "SELECT "
+ "ID,JOB_NAME,JOB_STATUS,CRON_EXPRESSION,CONCURRENT,DESCRIPTION,JOB_GROUP,"
+ "TARGET_OBJECT,TARGET_METHOD,IS_SPRING_BEAN,CLAZZ,CHILD_JOBS "
+ "FROM QUARTZ_SCHEDULEJOB WHERE ID = ‘"+id+"‘";
rs = smt.executeQuery(sql);
while (rs.next()) {
sj = new ScheduleJob();
sj.setJobId(rs.getString("ID"));
sj.setJobName(rs.getString("JOB_NAME"));
sj.setJobGroup(rs.getString("JOB_GROUP"));
sj.setJobStatus(rs.getString("JOB_STATUS"));
sj.setCronExpression(null);//子任务不要
// sj.setCronExpression(rs.getString("CRON_EXPRESSION"));
sj.setDescription(rs.getString("DESCRIPTION"));
sj.setTargetMethod(rs.getString("TARGET_METHOD"));
sj.setTargetObject(rs.getString("TARGET_OBJECT"));
sj.setIsSpringBean(rs.getString("IS_SPRING_BEAN"));
sj.setClazz(rs.getString("CLAZZ"));
sj.setConcurrent(rs.getString("CONCURRENT"));
sj.setChildJobs(rs.getString("CHILD_JOBS"));
}
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return sj;
}
/**
* 根据主工作名称获取子工作
* @param mainJob
*/
public static String getChildsJobByMainJobName(String mainJob) {
Connection con = null;
Statement smt = null;
ResultSet rs = null;
con = new DBUtil().getDBConnection();
String result = "";
try {
if (con != null) {
smt = con.createStatement();
con.setAutoCommit(false);
//因为只是主任务需要cron子任务不需要,所以只需要查找childs_jobs
String sql = "SELECT CHILD_JOBS FROM QUARTZ_SCHEDULEJOB WHERE JOB_NAME = ‘"+mainJob+"‘";
rs = smt.executeQuery(sql);
if(rs.next()){
result = rs.getString(1);
}
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
public Connection getDBConnection() {
Connection conn = null;
String driver = "";
String url = "";
String user = "";
String password = "";
Properties props = new Properties();
try {
props.load(this.getClass().getClassLoader().getResourceAsStream("default.properties"));
driver = props.getProperty("jdbc.driver");
url = props.getProperty("jdbc.url");
user = props.getProperty("jdbc.username");
password = props.getProperty("jdbc.password");
Class.forName(driver);
conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
- com.cn.util.QuartzUtil
package com.cn.util;
import java.util.ArrayList;
import java.util.List;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdScheduler;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import com.cn.model.ScheduleJob;
/**
* Quartz工具类
*
* @author 杨润康Bla
*
*/
public class QuartzUtil {
// private static Logger logger = Logger.getLogger(QuartzUtil.class);
// 主工作需要保持名称唯一
public static List<String> jobNames = new ArrayList<String>();
// 公用Scheduler
public static Scheduler scheduler = (StdScheduler) SpringContextUtil.getApplicationContext()
.getBean("schedulerFactoryBean"); // 同一个对象
// 循环队列取出目标工作对象
public static String getScheduleJobName(String jobName) {
if (jobNames.contains(jobName)) { // 如果队列中有id,说明其子任务需要执行
return jobName;
}
return null;
}
/**
* 创建子任务
* @param job
* @throws Exception
*/
public static void createChildJob(ScheduleJob job) throws Exception {
job.setJobName(UUIDGenerator.getUUID()+job.getJobName()); //只是当前任务的名字而已,暂时的标记作用,不影响配置
MethodInvokingJobDetailFactoryBean methodInvJobDetailFB = new MethodInvokingJobDetailFactoryBean();
// 设置Job组名称
methodInvJobDetailFB.setGroup(job.getJobGroup());
// 设置Job名称
methodInvJobDetailFB.setName(job.getJobName()); // 注意设置的顺序,如果在管理Job类提交到计划管理类之后设置就会设置不上
// 定义的任务类为Spring的定义的Bean则调用 getBean方法
if (job.getIsSpringBean().equals("1")) {// 是Spring中定义的Bean
methodInvJobDetailFB
.setTargetObject(SpringContextUtil.getApplicationContext().getBean(job.getTargetObject()));
} else {// 不是就直接new
methodInvJobDetailFB.setTargetObject(Class.forName(job.getClazz()).newInstance());
}
// 设置任务方法
methodInvJobDetailFB.setTargetMethod(job.getTargetMethod());
// 将管理Job类提交到计划管理类
methodInvJobDetailFB.afterPropertiesSet();
/** 并发设置 */
methodInvJobDetailFB.setConcurrent(job.getConcurrent().equals("1") ? true : false);
JobDetail jobDetail = (JobDetail) methodInvJobDetailFB.getObject();// 动态
jobDetail.getJobDataMap().put("scheduleJob", job);
// 不按照表达式
Trigger trigger = TriggerBuilder.newTrigger()
// 保证键值不一样
.withIdentity(job.getJobName(), job.getJobGroup())
// .usingJobData("","")//可以存储数据
.build();
/**
原理:
因为是立即执行,没有用到表达式嘛,所以按照实际的调度创建顺序依次执行
*/
QuartzUtil.scheduler.standby(); //暂时停止 任务都安排完之后统一启动 解决耗时任务按照顺序部署后执行紊乱的问题
QuartzUtil.scheduler.scheduleJob(jobDetail, trigger);// 注入到管理类
// logger.info("子:" + job.getJobGroup() + "." + job.getJobName() + "创建完毕");
}
/**
* 执行子任务
* @param mainJob
* @throws Exception
* @throws Exception
*/
public static void executeChildJobs(String mainJob) {
if(mainJob!=null){
String childs = DBUtil.getChildsJobByMainJobName(mainJob);
if(null != childs){ //有子任务时才执行
String[] childsJobId = DBUtil.getChildsJobByMainJobName(mainJob).split(",");
for(String childJobId : childsJobId){
// System.out.println(childJobId); 打印当前任务的子任务
if(!"".equals(childJobId)){
ScheduleJob job = DBUtil.getScheduleJobById(childJobId);
try {
QuartzUtil.createChildJob(job);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
try {
QuartzUtil.scheduler.start();//任务安排完之后启动 解决耗时任务按照顺序部署后执行紊乱的问题
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
- com.cn.util.SpringContextUtil
package com.cn.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* Spring上下文工具
* @author 杨润康Bla
* */
public class SpringContextUtil implements ApplicationContextAware {
// Spring应用上下文环境
private static ApplicationContext applicationContext;
/**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境
*
* @param applicationContext
*/
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextUtil.applicationContext = applicationContext;
}
/**
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 获取对象
*
* @param name
* @return Object
* @throws BeansException
*/
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
}
- com.cn.util.Util
package com.cn.util;
/**
* 工具
* @author 杨润康
*
*/
public class Util {
public static void time_6s(){
try {
Thread.sleep(6*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void time_10s(){
try {
Thread.sleep(10*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void time_8s(){
try {
Thread.sleep(8*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.cn.util;
import java.util.UUID;
public class UUIDGenerator {
public static String getUUID(){
String s = UUID.randomUUID().toString();
return s.substring(0, 8) + s.substring(9, 13) + s.substring(14, 18) + s.substring(19, 23) + s.substring(24);
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:c="http://www.springframework.org/schema/c" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- ==========动态添加任务START========== -->
<!-- 注入StdSchedulerFactory 注入这个类可以使用quartz.properties配置文件 -->
<bean id="stdSchedulerFactory" class="org.quartz.impl.StdSchedulerFactory" />
<!-- 注册SpringContextUtil用于获取ApplicationContext -->
<bean id="springContextUtil" class="com.cn.util.SpringContextUtil"></bean>
<!-- 注册QuartzJobFactory -->
<bean id="quartzJobFactory" class="com.cn.quartz.inputs.QuartzJobFactory" />
<!-- 主定时计划 -->
<bean id="managerTriggerBean"
class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
<property name="jobDetail" ref="methodInvokingJobDetailFactoryBean" />
<!-- 延迟启动 -->
<property name="startDelay" value="1000"></property>
<property name="repeatInterval" value="6000"></property>
</bean>
<!-- 注册SchedulerFactoryBean -->
<bean id="schedulerFactoryBean"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="managerTriggerBean" />
</list>
</property>
</bean>
<!-- jobDetail -->
<bean id="methodInvokingJobDetailFactoryBean" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="quartzJobFactory" />
<property name="targetMethod" value="arrageScheduleJob" />
</bean>
<!-- ==========动态添加任务END========== -->
<!-- 扫表任务包 -->
<context:component-scan base-package="com.cn.tasks"></context:component-scan>
</beans>
jdbc.validate=SELECT 1 FROM DUAL
jdbc.driver=oracle.jdbc.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.username=quartz
jdbc.password=quartz
SERVER_HOME=D:/javaTool/luna/ws/.metadata/.plugins/org.eclipse.wst.server.core/tmp0
#\u8f93\u51fa\u7ea7\u522b\uff1aDEBUG\u3001INFO\u3001WARN\u3001ERROR\u548cFATAL
#stdout,dailyRollingFile\u8f93\u51fa\u76ee\u7684\u5730
log4j.rootLogger=DEBUG,stdout,dailyRollingFile
#Root Logger Configuration
#\u8f93\u51fa\u76ee\u7684\u5730
#org.apache.log4j.ConsoleAppender\uff08\u63a7\u5236\u53f0\uff09
#org.apache.log4j.FileAppender\uff08\u6587\u4ef6\uff09
#org.apache.log4j.DailyRollingFileAppender\uff08\u6bcf\u5929\u4ea7\u751f\u4e00\u4e2a\u65e5\u5fd7\u6587\u4ef6\uff09
#org.apache.log4j.RollingFileAppender\uff08\u6587\u4ef6\u5927\u5c0f\u5230\u8fbe\u6307\u5b9a\u5c3a\u5bf8\u7684\u65f6\u5019\u4ea7\u751f\u65b0\u6587\u4ef6\uff09
#org.apache.log4j.WriterAppender\uff08\u5c06\u65e5\u5fd7\u4fe1\u606f\u4ee5\u6d41\u683c\u5f0f\u53d1\u9001\u5230\u4efb\u610f\u6307\u5b9a\u7684\u5730\u65b9\uff09
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
#org.apache.log4j.HTMLLayout\uff08\u4ee5HTML\u8868\u683c\u5f62\u5f0f\u5e03\u5c40\uff09\uff0c
#org.apache.log4j.PatternLayout\uff08\u53ef\u4ee5\u7075\u6d3b\u5730\u6307\u5b9a\u5e03\u5c40\u6a21\u5f0f\uff09\uff0c
#org.apache.log4j.SimpleLayout\uff08\u5305\u542b\u65e5\u5fd7\u4fe1\u606f\u7684\u7ea7\u522b\u548c\u4fe1\u606f\u5b57\u7b26\u4e32\uff09\uff0c
#org.apache.log4j.TTCCLayout\uff08\u5305\u542b\u65e5\u5fd7\u4ea7\u751f\u7684\u65f6\u95f4\u3001\u7ebf\u7a0b\u3001\u7c7b\u522b\u7b49\u7b49\u4fe1\u606f\uff09
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#%p \u8f93\u51fa\u4f18\u5148\u7ea7\uff0c\u5373DEBUG\uff0cINFO\uff0cWARN\uff0cERROR\uff0cFATAL
#%r \u8f93\u51fa\u81ea\u5e94\u7528\u542f\u52a8\u5230\u8f93\u51fa\u8be5log\u4fe1\u606f\u8017\u8d39\u7684\u6beb\u79d2\u6570
#%c \u8f93\u51fa\u6240\u5c5e\u7684\u7c7b\u76ee\uff0c\u901a\u5e38\u5c31\u662f\u6240\u5728\u7c7b\u7684\u5168\u540d
#%t \u8f93\u51fa\u4ea7\u751f\u8be5\u65e5\u5fd7\u4e8b\u4ef6\u7684\u7ebf\u7a0b\u540d
#%n \u8f93\u51fa\u4e00\u4e2a\u56de\u8f66\u6362\u884c\u7b26\uff0cWindows\u5e73\u53f0\u4e3a\u201c\r\n\u201d\uff0cUnix\u5e73\u53f0\u4e3a\u201c\n\u201d
#%d \u8f93\u51fa\u65e5\u5fd7\u65f6\u95f4\u70b9\u7684\u65e5\u671f\u6216\u65f6\u95f4\uff0c\u9ed8\u8ba4\u683c\u5f0f\u4e3aISO8601\uff0c\u4e5f\u53ef\u4ee5\u5728\u5176\u540e\u6307\u5b9a\u683c\u5f0f\uff0c\u6bd4\u5982\uff1a%d{yyy MMM dd HH:mm:ss,SSS}\uff0c\u8f93\u51fa\u7c7b\u4f3c\uff1a 2002\u5e7410\u670818\u65e5 22\uff1a10\uff1a28\uff0c921
#%l \u8f93\u51fa\u65e5\u5fd7\u4e8b\u4ef6\u7684\u53d1\u751f\u4f4d\u7f6e\uff0c\u5305\u62ec\u7c7b\u76ee\u540d\u3001\u53d1\u751f\u7684\u7ebf\u7a0b\uff0c\u4ee5\u53ca\u5728\u4ee3\u7801\u4e2d\u7684\u884c\u6570\u3002\u4e3e\u4f8b\uff1aTestlog4.main(TestLog4.java:10)
log4j.appender.stdout.layout.ConversionPattern=%d{HH\:mm:\ss} [%-5p] %C{1} %m%n
log4j.appender.dailyRollingFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.dailyRollingFile.File=gdc.log
log4j.appender.dailyRollingFile.DatePattern=‘.‘yyyy-MM-dd
log4j.appender.dailyRollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.dailyRollingFile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%-5p] %m%n
# SqlMap logging configuration...
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.org.springframework=ERROR
log4j.logger.freemarker=ERROR
log4j.logger.org.apache.struts2=ERROR
log4j.logger.org.apache.commons=ERROR
log4j.logger.com.mchange=ERROR
log4j.logger.org.quartz=ERROR
log4j.logger.com.opensymphony.xwork2=ERROR
log4j.logger.com.opensymphony.xwork2.ActionSupport=ERROR
#log4j.logger.org.springframework.jdbc.datasource=DEBUG
#log4j.logger.org.springframework.jdbc=DEBUG
#log4j.logger.org.springframework.transaction=DEBUG
### \u8f93\u51fa\u5230\u65e5\u5fd7\u6587\u4ef6 ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
## \u8f93\u51faDEBUG\u7ea7\u522b\u4ee5\u4e0a\u7684\u65e5\u5fd7
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### \u4fdd\u5b58\u5f02\u5e38\u4fe1\u606f\u5230\u5355\u72ec\u6587\u4ef6 ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = logs/error.log
## \u5f02\u5e38\u65e5\u5fd7\u6587\u4ef6\u540d
log4j.appender.D.Append = true
log4j.appender.D.Threshold = ERROR
## \u53ea\u8f93\u51faERROR\u7ea7\u522b\u4ee5\u4e0a\u7684\u65e5\u5fd7!!!
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
##集群配置
org.quartz.scheduler.instanceName: DefaultQuartzScheduler
org.quartz.scheduler.rmi.export: false
org.quartz.scheduler.rmi.proxy: false
org.quartz.scheduler.wrapJobExecutionInUserTransaction: false
#
org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount: 10
org.quartz.threadPool.threadPriority: 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true
org.quartz.jobStore.misfireThreshold: 60000
#
##默认配置,数据保存到内存
org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore
#持久化配置 一持久化数据库就出问题
#org.quartz.jobStore.class:org.quartz.impl.jdbcjobstore.JobStoreTX
#org.quartz.jobStore.driverDelegateClass:org.quartz.impl.jdbcjobstore.StdJDBCDelegate
#org.quartz.jobStore.useProperties:false
#数据库表前缀
#org.quartz.jobStore.tablePrefix:QRTZ_
#org.quartz.jobStore.dataSource = qzDS
#org.quartz.dataSource.qzDS.driver = oracle.jdbc.OracleDriver
#org.quartz.dataSource.qzDS.URL = jdbc:oracle:thin:@10.56.6.12:1521:orcl
#org.quartz.dataSource.qzDS.user = quartz
#org.quartz.dataSource.qzDS.password = quartz
##############################集群###########################################
##============================================================================
## Configure Main Scheduler Properties
##============================================================================
#org.quartz.scheduler.instanceName = DefaultQuartzScheduler
#org.quartz.scheduler.instanceId = AUTO
#org.quartz.scheduler.rmi.export = false
#org.quartz.scheduler.rmi.proxy = false
#org.quartz.scheduler.wrapJobExecutionInUserTransaction = false
#
##============================================================================
## Configure ThreadPool
##============================================================================
#org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
#org.quartz.threadPool.threadCount = 10
#org.quartz.threadPool.threadPriority = 5
#org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true
#
##============================================================================
## Configure JobStore
##============================================================================
#org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
#org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.oracle.OracleDelegate
#org.quartz.jobStore.misfireThreshold = 60000
#org.quartz.jobStore.useProperties = false
#org.quartz.jobStore.tablePrefix = QRTZ_
#org.quartz.jobStore.dataSource = myDS
#
#org.quartz.jobStore.isClustered = true
#org.quartz.jobStore.clusterCheckinInterval = 15000
#
#org.quartz.jobStore.dataSource = qzDS
#org.quartz.dataSource.qzDS.driver = oracle.jdbc.OracleDriver
#org.quartz.dataSource.qzDS.URL = jdbc:oracle:thin:@10.56.6.12:1521:orcl
#org.quartz.dataSource.qzDS.user = quartz
#org.quartz.dataSource.qzDS.password = quartz
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Spring_Quartz_Mybatis</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-quartz.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Quartz任务调度[Spring+Quartz结合]_实现任务的动态添加、修改和删除
标签:
原文地址:http://blog.csdn.net/yangrunkangbla/article/details/51473169