Quartz是一個優秀的任務調度框架,完全基於Java實現,功能強大,易於集成,最近在寫了一個小項目,算是對之前接觸到的技術做一個總結吧,在這個項目中使用Quartz實現對任務的監控,最終實現的效果如圖:
添加效果:
目前已經實現了對Quartz任務的動態添加、暫停、恢復、刪除等功能,該項目中使用的是CronTrigger,CronTrigger可以配置靈活的時間規則,是和企業級的應用。
JobDetail界面效果圖:
對quartz的研究還在繼續,項目也做了不少了,暫時真正研究Quartz應該算剛剛開始,還屬於新人階段,還有一些問題需要解決,在此做一個總結,同時也希望志同道合之人指點一二,互相學習,互相進步吧。
項目簡介:
項目名稱:cube
項目使用的服務器:tomcat
項目框架:Struts+Spring+Hibernate
數據庫:Mysql
開發工具:eclipse
前端:easyui
項目模塊如圖:
上班族一名,只能趁工作之餘來寫代碼,目前只是實現了系統管理和作業監控部分,系統管理整體使用Shiro實現,目前可以控制到Button級別,作業監控使用Quartz實現
Quartz中 quartz-2.1.7\quartz-2.1.7\docs\dbTables 中有我們實現監控所需的表,依照數據庫選擇
Quartz數據庫核心表如下:
Table Name | Description |
---|---|
QRTZ_CALENDARS | 存儲Quartz的Calendar信息 |
QRTZ_CRON_TRIGGERS | 存儲CronTrigger,包括Cron表達式和時區信息 |
QRTZ_FIRED_TRIGGERS | 存儲與已觸發的Trigger相關的狀態信息,以及相聯Job的執行信息 |
QRTZ_PAUSED_TRIGGER_GRPS | 存儲已暫停的Trigger組的信息 |
QRTZ_SCHEDULER_STATE | 存儲少量的有關Scheduler的狀態信息,和別的Scheduler實例 |
QRTZ_LOCKS | 存儲程序的悲觀鎖的信息 |
QRTZ_JOB_DETAILS | 存儲每一個已配置的Job的詳細信息 |
QRTZ_JOB_LISTENERS | 存儲有關已配置的JobListener的信息 |
QRTZ_SIMPLE_TRIGGERS | 存儲簡單的Trigger,包括重複次數、間隔、以及已觸的次數 |
QRTZ_BLOG_TRIGGERS | Trigger作爲Blob類型存儲 |
QRTZ_TRIGGER_LISTENERS | 存儲已配置的TriggerListener的信息 |
QRTZ_TRIGGERS | 存儲已配置的Trigger的信息 |
下面是Quartz任務監控的具體配置和實現:
Spring配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.cube.*" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="cube"></property>
<!-- value 對應persistence.xml中的 persistence-unit name -->
</bean>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- login action -->
<tx:annotation-driven transaction-manager="txManager" />
</beans>
applicationContext-quartz.xml 配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean name="quartzScheduler"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="applicationContextSchedulerContextKey" value="applicationContextKey" />
<property name="configLocation" value="classpath:quartz.properties" />
</bean>
<bean name="jobDetail"
class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass">
<value>com.cube.service.quartz.QuartzJobService</value>
</property>
<property name="durability" value="true" />
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/cube?useUnicode=true&characterEncoding=UTF8" />
<property name="user" value="root" />
<property name="password" value="" />
<property name="initialPoolSize" value="10" />
<property name="minPoolSize" value="10" />
<property name="maxPoolSize" value="25" />
<property name="acquireIncrement" value="5" />
<property name="maxIdleTime" value="7200" />
</bean>
</beans>
quartz.properties 配置
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.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.tablePrefix = QRTZ_
org.quartz.jobStore.isClustered = false
org.quartz.jobStore.maxMisfiresToHandleAtATime=1
任務調度器Service
public interface SchedulerService {
public List<Map<String, Object>> getQrtzTriggers();
/**
* 根據 Quartz Cron Expression 調試任務
*
* @param name Quartz CronTrigger名稱
* @param group Quartz CronTrigger組
* @param cronExpression Quartz Cron 表達式,如 "0/10 * * ? * * *"等
*/
void schedule(String name, String group, String cronExpression);
/**
* 根據 Quartz Cron Expression 調試任務
*
* @param name Quartz CronTrigger名稱
* @param group Quartz CronTrigger組
* @param cronExpression Quartz CronExpression
*/
void schedule(String name, String group, CronExpression cronExpression);
/**
*
* @param name Quartz CronTrigger名稱
* @param group Quartz CronTrigger組
* @param cronExpression Quartz CronExpression
*/
void schedule(String name, String group);
void schedule(Map<String, Object> map);
/**
* 暫停觸發器
*
* @param triggerName 觸發器名稱
*/
void pauseTrigger(String triggerName);
/**
* 暫停觸發器
*
* @param triggerName 觸發器名稱
* @param group 觸發器組
*/
void pauseTrigger(String triggerName, String group);
/**
* 恢復觸發器
*
* @param triggerName 觸發器名稱
*/
void resumeTrigger(String triggerName);
/**
* 恢復觸發器
*
* @param triggerName 觸發器名稱
* @param group 觸發器組
*/
void resumeTrigger(String triggerName, String group);
/**
* 刪除觸發器
*
* @param triggerName 觸發器名稱
* @return
*/
boolean removeTrigdger(String triggerName);
/**
* 刪除觸發器
*
* @param triggerName 觸發器名稱
* @param group 觸發器組
* @return
*/
boolean removeTrigdger(String triggerName, String group);
}
任務調度器Service實現類
@Transactional
@Service("schedulerService")
public class SchedulerServiceImpl implements SchedulerService {
@Resource(name = "quartzDao")
private QuartzDao quartzDao;
@Autowired
private Scheduler scheduler;
@Autowired
private JobDetail jobDetail;
private static final String NULLSTRING = null;
private static final Date NULLDATE = null;
/**
*
* @param name
* @param group
* @param cronExpression
* @see com.cube.service.SchedulerService#schedule(java.lang.String, java.lang.String,
* java.lang.String)
*/
public void schedule(String name, String group, String cronExpression) {
try {
schedule(name, group, new CronExpression(cronExpression));
} catch (ParseException e) {
e.printStackTrace();
}
}
/**
* @param name
* @param group
* @param cronExpression
* @see com.cube.service.SchedulerService#schedule(java.lang.String, java.lang.String,
* org.quartz.CronExpression)
*/
public void schedule(String name, String group, CronExpression cronExpression) {
if (name == null || name.trim().equals("")) {
name = UUID.randomUUID().toString();
}
CronTriggerImpl trigger = new CronTriggerImpl();
trigger.setCronExpression(cronExpression);
TriggerKey triggerKey = new TriggerKey(name, group);
trigger.setJobName(jobDetail.getKey().getName());
trigger.setKey(triggerKey);
try {
scheduler.addJob(jobDetail, true);
if (scheduler.checkExists(triggerKey)) {
scheduler.rescheduleJob(triggerKey, trigger);
} else {
scheduler.scheduleJob(trigger);
}
} catch (SchedulerException e) {
throw new IllegalArgumentException(e);
}
}
/**
* @param map
* @see com.cube.service.SchedulerService#schedule(java.util.Map)
*/
public void schedule(Map<String, Object> map) {
// TODO Auto-generated method stub
}
/**
* @param triggerName
* @see com.cube.service.SchedulerService#pauseTrigger(java.lang.String)
*/
public void pauseTrigger(String triggerName) {
// TODO Auto-generated method stub
}
/**
* @param triggerName
* @param group
* @see com.cube.service.SchedulerService#pauseTrigger(java.lang.String, java.lang.String)
*/
public void pauseTrigger(String triggerName, String group) {
try {
scheduler.pauseTrigger(new TriggerKey(triggerName, group));
} catch (SchedulerException e) {
e.printStackTrace();
}
}
/**
* @param triggerName
* @see com.cube.service.SchedulerService#resumeTrigger(java.lang.String)
*/
public void resumeTrigger(String triggerName) {
// TODO Auto-generated method stub
}
/**
* @param triggerName
* @param group
* @see com.cube.service.SchedulerService#resumeTrigger(java.lang.String, java.lang.String)
*/
public void resumeTrigger(String triggerName, String group) {
TriggerKey triggerKey = new TriggerKey(triggerName, group);
try {
scheduler.resumeTrigger(triggerKey);
} catch (SchedulerException e) {
e.printStackTrace();
}
}
/**
* @param triggerName
* @return
* @see com.cube.service.SchedulerService#removeTrigdger(java.lang.String)
*/
public boolean removeTrigdger(String triggerName) {
return removeTrigdger(triggerName, NULLSTRING);
}
/**
* @param triggerName
* @param group
* @return
* @see com.cube.service.SchedulerService#removeTrigdger(java.lang.String, java.lang.String)
*/
public boolean removeTrigdger(String triggerName, String group) {
TriggerKey triggerKey = new TriggerKey(triggerName, group);
try {
scheduler.pauseTrigger(triggerKey);// 停止觸發器
return scheduler.unscheduleJob(triggerKey);// 移除觸發器
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
}
/**
* @return
* @see com.cube.service.SchedulerService#getQrtzTriggers()
*/
public List<Map<String, Object>> getQrtzTriggers() {
return quartzDao.getQrtzTriggers();
}
/**
* @param name
* @param group
* @see com.cube.service.SchedulerService#schedule(java.lang.String, java.lang.String)
*/
public void schedule(String name, String group) {
schedule(name, group, NULLSTRING);
}
}
QuartzDao實現
@Repository("quartzDao")
public class QuartzDao {
private DataSource dataSource;
@Autowired
public void setDataSource(@Qualifier("dataSource") DataSource dataSource) {
this.dataSource = dataSource;
}
// 查詢Trigger
public List<Map<String, Object>> getQrtzTriggers() {
List<Map<String, Object>> results = getJdbcTemplate().queryForList(
"select * from QRTZ_TRIGGERS order by start_time");
long val = 0;
String temp = null;
for (Map<String, Object> map : results) {
temp = MapUtils.getString(map, "trigger_name");
if (StringUtils.indexOf(temp, "&") != -1) {
map.put("display_name", StringUtils.substringBefore(temp, "&"));
} else {
map.put("display_name", temp);
}
val = MapUtils.getLongValue(map, "next_fire_time");
if (val > 0) {
map.put("next_fire_time", DateFormatUtils.format(val, "yyyy-MM-dd HH:mm:ss"));
}
val = MapUtils.getLongValue(map, "prev_fire_time");
if (val > 0) {
map.put("prev_fire_time", DateFormatUtils.format(val, "yyyy-MM-dd HH:mm:ss"));
}
val = MapUtils.getLongValue(map, "start_time");
if (val > 0) {
map.put("start_time", DateFormatUtils.format(val, "yyyy-MM-dd HH:mm:ss"));
}
val = MapUtils.getLongValue(map, "end_time");
if (val > 0) {
map.put("end_time", DateFormatUtils.format(val, "yyyy-MM-dd HH:mm:ss"));
}
map.put("trigger_state", Constant.status.get(MapUtils.getString(map, "trigger_state")));
}
return results;
}
private JdbcTemplate getJdbcTemplate() {
return new JdbcTemplate(this.dataSource);
}
}
JobClass
public class QuartzJobService extends QuartzJobBean {
// 負責所有任務的調度
private TaskService taskService;
/**
* @param context
* @throws JobExecutionException
* @see org.springframework.scheduling.quartz.QuartzJobBean#executeInternal(org.quartz.JobExecutionContext)
*/
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
String triggerName = context.getTrigger().getKey().getName();
taskService = (TaskService) getApplicationContext(context).getBean("taskService");
taskService.execute(triggerName);
}
private ApplicationContext getApplicationContext(final JobExecutionContext jobexecutioncontext) {
try {
return (ApplicationContext) jobexecutioncontext.getScheduler().getContext()
.get("applicationContextKey");
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
}
}
TaskService所有任務的統一調用接口
public interface TaskService {
/**
* @param triggerName
*/
public void execute(String triggerName);
}
@Transactional
@Service("taskService")
public class TaskServiceImpl implements TaskService {
@Resource(name = "reportService")
private ReportService reportService;
/**
* 根據TriggerName 調用不同的業務邏輯service
*
* @param triggerName
* @see com.cube.service.TaskService#execute(java.lang.String)
*/
public void execute(String triggerName) {
if ("reportTigger".equalsIgnoreCase(triggerName)) {
reportService.createReport();
} else {
System.out.println(triggerName + ":企業業務邏輯");
}
}
}
/**
* 任務調度器
*
*/
@Controller
@Scope("prototype")
public class TriggerAction extends BaseAction<TriggerEntity> {
/** */
private static final long serialVersionUID = -3326354633384499660L;
private TriggerEntity triggerEntity = getModel();
private Map jsonMap = new HashMap();
@Resource(name = "schedulerService")
private SchedulerService schedulerService;
/**
* 跳轉到tigger 管理界面
*
* @return
*/
public String trigger() {
return "trigger";
}
/**
* 分頁查詢Trigger
*
* @return
*/
public String list() {
List<Map<String, Object>> list = schedulerService.getQrtzTriggers();
jsonMap.put("rows", list);
jsonMap.put("total", list.size());
return "list";
}
/**
* 添加觸發器
*
* @return
*/
public String save() {
// 獲取界面以參數
String triggerName = triggerEntity.getTrigger_name();
String cronExpression = triggerEntity.getCron();
String group = triggerEntity.getTrigger_group();
schedulerService.schedule(triggerName, group, cronExpression);
jsonMap.put("flag", true);
return "save";
}
/**
* 暫停
*
* @return
*/
public String pause() {
schedulerService.pauseTrigger(triggerEntity.getTrigger_name(),
triggerEntity.getTrigger_group());
jsonMap.put("flag", true);
return "pause";
}
/**
* Trigger恢復
*
* @return
*/
public String play() {
schedulerService.resumeTrigger(triggerEntity.getTrigger_name(),
triggerEntity.getTrigger_group());
jsonMap.put("flag", true);
return "play";
}
/**
* 刪除
*
* @return
*/
public String deleteTrigger() {
schedulerService.removeTrigdger(triggerEntity.getTrigger_name(),
triggerEntity.getTrigger_group());
jsonMap.put("flag", true);
return "deleteTrigger";
}
public Map getJsonMap() {
return jsonMap;
}
public void setJsonMap(Map jsonMap) {
this.jsonMap = jsonMap;
}
}
參考資料:
https://www.ibm.com/developerworks/cn/opensource/os-cn-quartz/
http://tech.meituan.com/mt-crm-quartz.html