spring quartz 总结:
引用:
1 http://blog.csdn.net/evankaka/article/details/45540885
2 http://www.cnblogs.com/maiyu-d/archive/2012/12/13/2816271.html
3 http://haiziwoainixx.iteye.com/blog/1838055
1 spring quartz 非持久化 存储配置
2 spring quartz 持久化 存储配置
spring 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
" >
<!-- 增加定时器配置 -->
<!-- 线程执行器配置,用于任务注册 -->
<bean id="executor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="20" />
<property name="maxPoolSize" value="150" />
<property name="queueCapacity" value="500" />
</bean>
<bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" lazy-init="true">
<property name="configLocation" value="classpath:quartz.properties" />
<property name="applicationContextSchedulerContextKey" value="applicationContextKey" />
<property name="autoStartup" value="true" />
<property name="taskExecutor" ref="executor" />
<property name="startupDelay" value="5"/>
</bean>
<!--加载可执行的任务 启动quartz库中job 依赖于springContextHolder启动后init-method-->
<bean id="schedule-service-QuartzManager"
class="com.movikr.svc.schedule.service.task.config.QuartzManager"
init-method="initJobs" depends-on="springContextHolder" />
</beans>
2 属性文件 quartz.properties
###################
#ContextConfig
###################
#============================================================================
# Configure Main Scheduler Properties
# Needed to manage cluster instances
#============================================================================
org.quartz.scheduler.instanceName=DefaultQuartzScheduler
org.quartz.scheduler.wrapJobExecutionInUserTransaction=false
org.quartz.scheduler.instanceId=AUTO
#============================================================================
# Configure rmi
#============================================================================
#org.quartz.scheduler.rmi.export=true
#org.quartz.scheduler.rmi.createRegistry=true
#org.quartz.scheduler.rmi.registryHost=localhost
#org.quartz.scheduler.rmi.registryPort=1099
#org.quartz.scheduler.rmi.serverPort=1100
org.quartz.scheduler.rmi.export=false
org.quartz.scheduler.rmi.proxy=false
#============================================================================
# Configure ThreadPool
#============================================================================
org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount=50
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.StdJDBCDelegate
org.quartz.jobStore.tablePrefix=QRTZ_
org.quartz.jobStore.dataSource=myDS
org.quartz.jobStore.misfireThreshold=60000
org.quartz.jobStore.isClustered=true
org.quartz.jobStore.clusterCheckinInterval=1000
org.quartz.dataSource.myDS.connectionProvider.class=com.movikr.svc.schedule.service.task.config.CurrentQuartzConn
org.quartz.dataSource.myDS.driver=com.mysql.jdbc.Driver
org.quartz.dataSource.myDS.url=jdbc:mysql://172.16.30.52:3306/movikr_quartz?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull
org.quartz.dataSource.myDS.user=mapollo
org.quartz.dataSource.myDS.password=50957644874C93D49EBCBC9F685C149F
org.quartz.dataSource.myDS.maxConnections=10
3 currentQuartzConn.java
package com.movikr.svc.schedule.service.task.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.movikr.v2.core.utils.EncyptorUtils;
import org.quartz.SchedulerException;
import org.quartz.utils.ConnectionProvider;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
/**
* @author wz
*/
public class CurrentQuartzConn implements ConnectionProvider {
/**
* Default maximum number of database connections in the pool.
*/
public static final int DEFAULT_DB_MAX_CONNECTIONS = 10;
/**
* Default maximum number of database connections in the pool.
*/
public static final int DEFAULT_DB_MAX_CACHED_STATEMENTS_PER_CONNECTION = 120;
private String driver;
private String url;
private String user;
private String password;
private int maxConnections;
private int maxCachedStatementsPerConnection;
private int maxIdleSeconds;
private String validationQuery;
private int idleConnectionValidationSeconds;
private boolean validateOnCheckout;
private String discardIdleConnectionsSeconds;
private ComboPooledDataSource datasource;
/**
* 无参构造,必须要有[没有其他构造的话也可以不写]
*/
public CurrentQuartzConn() {
}
public Connection getConnection() throws SQLException {
return datasource.getConnection();
}
public void shutdown() throws SQLException {
datasource.close();
}
/**
* 初始化方法,应该在调用其setter后调用
*/
public void initialize() throws SQLException {
if (this.url == null) {
throw new SQLException("DBPool could not be created: DB URL cannot be null");
}
if (this.driver == null) {
throw new SQLException("DBPool driver could not be created: DB driver class name cannot be null!");
}
if (this.maxConnections < 0) {
throw new SQLException("DBPool maxConnectins could not be created: Max connections must be greater than zero!");
}
datasource = new ComboPooledDataSource();
try {
datasource.setDriverClass(this.driver);
} catch (PropertyVetoException e) {
try {
throw new SchedulerException("Problem setting driver class name on datasource: " + e.getMessage(), e);
} catch (SchedulerException e1) {
}
}
datasource.setJdbcUrl(this.url);
datasource.setUser(this.user);
datasource.setPassword(EncyptorUtils.decrypt(this.password));
datasource.setMaxPoolSize(this.maxConnections);
datasource.setMinPoolSize(1);
datasource.setMaxIdleTime(maxIdleSeconds);
datasource.setMaxStatementsPerConnection(this.maxCachedStatementsPerConnection);
if (this.validationQuery != null) {
datasource.setPreferredTestQuery(this.validationQuery);
if (!validateOnCheckout)
datasource.setTestConnectionOnCheckin(true);
else
datasource.setTestConnectionOnCheckout(true);
datasource.setIdleConnectionTestPeriod(this.idleConnectionValidationSeconds);
}
}
/*-------------------------------------------------
*
* setters 如果有必要,你可以添加一些getter
* ------------------------------------------------
*/
public void setDriver(String driver) {
this.driver = driver;
}
public void setUrl(String url) {
this.url = url;
}
public void setUser(String user) {
this.user = user;
}
public void setPassword(String password) {
this.password = password;
}
public void setMaxConnections(int maxConnections) {
this.maxConnections = maxConnections;
}
public void setMaxCachedStatementsPerConnection(int maxCachedStatementsPerConnection) {
this.maxCachedStatementsPerConnection = maxCachedStatementsPerConnection;
}
public void setMaxIdleSeconds(int maxIdleSeconds) {
this.maxIdleSeconds = maxIdleSeconds;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public void setIdleConnectionValidationSeconds(int idleConnectionValidationSeconds) {
this.idleConnectionValidationSeconds = idleConnectionValidationSeconds;
}
public void setValidateOnCheckout(boolean validateOnCheckout) {
this.validateOnCheckout = validateOnCheckout;
}
public void setDiscardIdleConnectionsSeconds(String discardIdleConnectionsSeconds) {
this.discardIdleConnectionsSeconds = discardIdleConnectionsSeconds;
}
public void setDatasource(ComboPooledDataSource datasource) {
this.datasource = datasource;
}
protected ComboPooledDataSource getDataSource() {
return datasource;
}
}
4 CancelPastLockOrderJob.java
public class CancelPastLockOrderJob extends MethodInvokingJobDetailFactoryBean.StatefulMethodInvokingJob {
private static final Logger LOG = LoggerFactory.getLogger(CancelPastLockOrderJob.class);
private static ProviderOrder providerOrder= SpringContextHolder.getBean("order-ProviderOrder");
protected static final Logger LOG_ERR = LoggerFactory.getLogger("ERROR");
@Override
protected void executeInternal(JobExecutionContext context)
throws JobExecutionException {
try {
LOG.info("resume cancel past order running ....");
providerOrder.cancelInvalidteOrder(new CancelInvalidateOrderReq());
LOG.info("end cancel past order running ....");
} catch (Exception e) {
JobExecutionException je = new JobExecutionException(e);
//je.setRefireImmediately(true);
LOG_ERR.error("", e);
throw je;
}
}
}
3 spring quartz 动态任务添加,手动执行 :
1 QuartzManager .java
package com.movikr.svc.schedule.service.task.config;
import com.movikr.svc.schedule.constants.DataDict;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* USER: samson
* TIME: 2015-10-09 13:10
* COMMENT: 定时任务管理器
* 修改任务配置 先停止(remove)触发器/任务 修改后 启动(add)
*/
@Component("schedule-service-QuartzManager")
public class QuartzManager {
private static final Logger LOG = LoggerFactory.getLogger(QuartzManager.class);
@Resource(name = "schedulerFactoryBean")
private Scheduler scheduler;
/**
* 初始化(spring启动 或其他)可运行的job 立即执行
* 配置成bean 指定init-method="initJobs" 后于springContextHolder bean初始化
*/
public void initJobs() throws SchedulerException {
// Set<JobKey> jobKeys = getAllJobs();
// if (jobKeys == null)
// return;
// for (JobKey jobKey : jobKeys) {
//
// //立即执行job(所有triggers)
// startJob(jobKey);
// //JobDetail job = scheduler.getJobDetail(jobKey);
//// List<? extends Trigger> triggers = getJobTriggers(jobKey);
//// for (Trigger trigger : triggers) {
//// scheduler.rescheduleJob(trigger.getKey(), trigger);
//// }
// }
if (!scheduler.isShutdown()) {
scheduler.start();
}
}
/**
* 添加job(新) 附带 trigger(新) 并启动
* 如果job存在 异常
* 如果trigger存在 异常
*
* @param jobName 任务名
* @param jobGroupName 任务组名
* @param triggerName 触发器名
* @param triggerGroupName 触发器组名
* @param jobClass 任务
* @param timeExpression 时间设置 core表达式
*/
public void addJobWithTrigger(String jobName, String jobGroupName,
String triggerName, String triggerGroupName,
String jobClass, String timeExpression, String desc) throws SchedulerException, ClassNotFoundException {
//Class clazz = Class.forName(jobClass);
Class clazz = QuartzManager.class.getClassLoader().loadClass(jobClass);
JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
addJobWithTrigger(jobKey, triggerKey, clazz, timeExpression, desc);
}
/**
* 添加job(新) 附带 trigger(新) 并启动
* 如果job存在 异常
* 如果trigger存在 异常
* @param jobKey
* @param triggerKey
* @param jobClass
* @param timeExpression
* @throws SchedulerException
*/
public void addJobWithTrigger(JobKey jobKey, TriggerKey triggerKey,
Class jobClass, String timeExpression, String desc) throws SchedulerException {
JobDetail job = JobBuilder.newJob(jobClass).withIdentity(jobKey)
.build();
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(timeExpression);
Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).startNow()
.withSchedule(scheduleBuilder).withDescription(desc).build();
//trigger状态 由none=>normal
scheduler.scheduleJob(job, trigger);
}
/**
* 添加触发器到任务并启动
* job存在则读取添加 不存在则创建
* trigger存在重新设置
* <p>
* 添加后会执行
*
* @param jobName 任务名
* @param jobGroupName 任务组名
* @param triggerName 触发器名
* @param triggerGroupName 触发器组名
* @param jobClass 任务
* @param timeExpression 时间设置 core表达式
*/
public void mergeTriggerToJob(String jobName, String jobGroupName,
String triggerName, String triggerGroupName,
String jobClass, String timeExpression) throws SchedulerException, ClassNotFoundException {
Class clazz = QuartzManager.class.getClassLoader().loadClass(jobClass);
JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
mergeTriggerToJob(jobKey, triggerKey, clazz, timeExpression);
}
/**
* 添加触发器到任务并启动
* job存在则读取添加 不存在则创建
* trigger存在重新设置
* <p>
* 添加后会执行
*
* @param jobKey 任务名
* @param triggerKey 触发器名
* @param jobClass 任务
* @param timeExpression 时间设置 core表达式
*/
public void mergeTriggerToJob(JobKey jobKey, TriggerKey triggerKey,
String jobClass, String timeExpression) throws SchedulerException, ClassNotFoundException {
Class clazz = QuartzManager.class.getClassLoader().loadClass(jobClass);
mergeTriggerToJob(jobKey, triggerKey, clazz, timeExpression);
}
/**
* 添加触发器到任务并启动
* job存在则读取添加 不存在则创建
* trigger存在重新设置
* <p>
* 1.如果添加新的job和trigger(jobName和triggerName不同)不需要startNow() 便会立即执行
* 2.如果是修改现有的job和trigger startNow():表示立即执行 不会等待之前的job完成再取执行而是立即执行
* 3.在初始化init 执行start或triggerJob 会把所有的job启动 那么如果修改job和trigger不startNow 则会一直等待完成 再执行新的
* 4.如果不执行init 执行merge原有的job和trigger 不需要startNow 立即执行新的
*
*
* <p>
* 添加后会执行
*
* @param jobKey 任务名
* @param triggerKey 触发器名
* @param jobClass 任务
* @param timeExpression 时间设置 core表达式
*/
@SuppressWarnings("unchecked")
public void mergeTriggerToJob(JobKey jobKey, TriggerKey triggerKey,
Class jobClass, String timeExpression) throws SchedulerException {
JobDetail job = null;
//获取job
if (scheduler.checkExists(jobKey)) {
job = scheduler.getJobDetail(jobKey);
} else {
// 任务名,任务组,任务执行类
job = JobBuilder.newJob(jobClass).withIdentity(jobKey)
.build();
}
if (scheduler.checkExists(triggerKey)) {
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(timeExpression);
CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
// Trigger trigger = cronTrigger.getTriggerBuilder().withIdentity(triggerKey)
// .withSchedule(scheduleBuilder).build();
Trigger trigger = cronTrigger.getTriggerBuilder().withIdentity(triggerKey).startNow()
.withSchedule(scheduleBuilder).build();
//trigger状态 由normal=>normal
scheduler.rescheduleJob(triggerKey, trigger);
} else {
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(timeExpression);
Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).startNow()
.withSchedule(scheduleBuilder).build();
//trigger状态 由none=>normal
scheduler.scheduleJob(job, trigger);
}
}
/**
* 立即启动job
* 立即运行会立即执行一次任务,但是不影响当前已经运行中的任务(上次执行时间 下次执行时间)
*
* @param jobName
* @param jobGroupName
* @throws SchedulerException
*/
public void startJob(String jobName, String jobGroupName, Serializable jobParam) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
JobDataMap map = new JobDataMap();
map.put(DataDict.SCHEDULE_JOB_PARAM, jobParam);
//启动
if (scheduler.checkExists(jobKey)) {
scheduler.triggerJob(jobKey, map);
}
}
/**
* 立即启动job
* 立即运行会立即执行一次任务,但是不影响当前已经运行中的任务(上次执行时间 下次执行时间)
*
* @param jobKey
* @throws SchedulerException
*/
public void startJob(JobKey jobKey) throws SchedulerException {
//启动
if (scheduler.checkExists(jobKey)) {
scheduler.triggerJob(jobKey);
}
}
/**
* 获取所有job
*
* @return
* @throws SchedulerException
*/
public Set<JobKey> getAllJobs() throws SchedulerException {
GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
return jobKeys;
}
/**
* 获取正在运行的job
*
* @throws SchedulerException
*/
public List<JobDetail> getRunJobs() throws SchedulerException {
List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
List<JobDetail> jobList = new ArrayList<JobDetail>(executingJobs.size());
for (JobExecutionContext executingJob : executingJobs) {
JobDetail jobDetail = executingJob.getJobDetail();
jobList.add(jobDetail);
}
return jobList;
}
/**
* 返回当前job的所有triggers
*
* @return
* @throws SchedulerException
*/
public List<? extends Trigger> getJobTriggers(String jobName, String jobGroupName) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
return getJobTriggers(jobKey);
}
/**
* 返回当前job的所有triggers
*
* @param jobKey
* @return
* @throws SchedulerException
*/
public List<? extends Trigger> getJobTriggers(JobKey jobKey) throws SchedulerException {
if (!scheduler.checkExists(jobKey)) {
return null;
}
return scheduler.getTriggersOfJob(jobKey);
}
/**
* 获取触发器状态
*
* @param triggerName 触发器名
* @param triggerGroupName 触发器组名
* @return <p>
* NORMAL:运行
* PAUSED:job/trigger暂停
* NONE:job/trigger删除
* <p>
* NONE:Trigger已经完成,且不会在执行,或者找不到该触发器,或者Trigger已经被删除
* NORMAL:正常状态
* PAUSED:暂停状态
* COMPLETE:触发器完成,但是任务可能还正在执行中
* BLOCKED:线程阻塞状态
* ERROR:出现错误
* </p>
*/
public Trigger.TriggerState getTriggerStatus(String triggerName, String triggerGroupName)
throws SchedulerException {
TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
Trigger.TriggerState state = scheduler.getTriggerState(triggerKey);
return state;
}
/**
* 获取触发器状态
*
* @param triggerKey
* @return
* @throws SchedulerException
*/
public Trigger.TriggerState getTriggerStatus(TriggerKey triggerKey)
throws SchedulerException {
Trigger.TriggerState state = scheduler.getTriggerState(triggerKey);
return state;
}
public Trigger getTriigger(TriggerKey key) {
try {
return scheduler.getTrigger(key);
} catch (SchedulerException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取job
*
* @param jobKey
* @return
* @throws SchedulerException
*/
public JobDetail getJobDetail(JobKey jobKey)
throws SchedulerException {
JobDetail jobDetail = scheduler.getJobDetail(jobKey);
return jobDetail;
}
/**
* 获取job
*
* @return
* @throws SchedulerException
*/
public JobDetail getJobDetail(String jobName, String jobGroupName)
throws SchedulerException {
JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
return getJobDetail(jobKey);
}
/**
* 获取当前trigger cronExpression
*
* @param trigger
* @return
*/
public String getCronExpression(Trigger trigger) {
if (trigger instanceof CronTrigger) {
CronTrigger cronTrigger = (CronTrigger) trigger;
String cronExpression = cronTrigger.getCronExpression();
return cronExpression;
}
return null;
}
/**
* 修改trigger cronExpression
*
* @param triggerName
* @param triggerGroupName
* @param expression
* @throws SchedulerException
*/
public void modifyCornExpression(String triggerName, String triggerGroupName, String expression) throws SchedulerException {
TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
modifyCornExpression(triggerKey, expression);
}
/**
* 修改trigger cronExpression
*
* @param triggerKey
* @param expression
* @throws SchedulerException
*/
public void modifyCornExpression(TriggerKey triggerKey, String expression) throws SchedulerException {
if (scheduler.checkExists(triggerKey)) {
Trigger trigger = scheduler.getTrigger(triggerKey);
if (trigger instanceof CronTrigger) {
CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(expression);
cronTrigger = cronTrigger.getTriggerBuilder().withIdentity(triggerKey)
.withSchedule(scheduleBuilder).build();
scheduler.rescheduleJob(triggerKey, cronTrigger);
}
}
}
/**
* 暂停任务触发器
*
* @param triggerName 触发器名
* @param triggerGroupName 触发器组名
*/
public void pauseTrigger(String triggerName, String triggerGroupName)
throws SchedulerException {
TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
if (scheduler.checkExists(triggerKey)) {
scheduler.pauseTrigger(triggerKey);
}
}
/**
* 恢复任务触发器
*
* @param triggerName 触发器名
* @param triggerGroupName 触发器组名
*/
public void resumeTrigger(String triggerName, String triggerGroupName)
throws SchedulerException {
TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
if (scheduler.checkExists(triggerKey)) {
scheduler.resumeTrigger(triggerKey);
}
}
/**
* 暂停任务
*
* @param jobName 任务名
* @param jobGroupName 任务组名
* @throws SchedulerException
*/
public void pauseJob(String jobName, String jobGroupName)
throws SchedulerException {
JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
if (scheduler.checkExists(jobKey)) {
scheduler.pauseJob(jobKey);
}
}
/**
* 恢复任务
*
* @param jobName 任务名
* @param jobGroupName 任务组名
*/
public void resumeJob(String jobName, String jobGroupName)
throws SchedulerException {
JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
if (scheduler.checkExists(jobKey)) {
scheduler.resumeJob(jobKey);
}
}
/**
* 任务是否存在
*
* @param jobName 任务名
* @param jobGroupName 任务组名
* @return
*/
public boolean isJobExits(String jobName, String jobGroupName)
throws SchedulerException {
JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
return scheduler.checkExists(jobKey);
}
/**
* 触发器是否存在
*
* @param triggerName 触发器名
* @param triggerGroupName 触发器组名
* @return
*/
public boolean isTriggerExits(String triggerName, String triggerGroupName)
throws SchedulerException {
TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
return scheduler.checkExists(triggerKey);
}
/**
* 删除触发器
* 第三方 点击停止某个定制 调用此方法 移除存在的任务 即任务无效
*
* @param triggerName 触发器名
* @param triggerGroupName 触发器组名
*/
public void removeTrigger(String triggerName, String triggerGroupName)
throws SchedulerException {
TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
removeTrigger(triggerKey);
}
/**
* 删除触发器
* 第三方 点击停止某个定制 调用此方法 移除存在的任务 即任务无效
*
* @param triggerKey 触发器名
*/
public void removeTrigger(TriggerKey triggerKey)
throws SchedulerException {
if (scheduler.checkExists(triggerKey)) {
scheduler.pauseTrigger(triggerKey);// 停止触发器
scheduler.unscheduleJob(triggerKey);// 移除触发器
}
}
/**
* 删除任务
* 第三方 点击停止 调用此方法 移除存在的任务 即任务无效
*
* @param jobName 任务名
* @param jobGroupName 任务组名
*/
public void removeJob(String jobName, String jobGroupName)
throws SchedulerException {
JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
removeJob(jobKey);
}
/**
* 删除任务
* 第三方 点击停止 调用此方法 移除存在的任务 即任务无效
*
* @param jobKey
* @throws SchedulerException
*/
public void removeJob(JobKey jobKey)
throws SchedulerException {
if (scheduler.checkExists(jobKey)) {
// 删除(包括job和trigger)
scheduler.deleteJob(jobKey);
}
}
/**
* 关闭所有定时任务 资源 线程 所有方法将不能使用
*/
public void shutdownJobs() throws SchedulerException {
//等待完成任务后 关闭
scheduler.shutdown(true);
}
/**
* 清理所有定时任务(库中被删除job && trigger)
*/
public void clear() throws SchedulerException {
scheduler.clear();
}
}
2 QuartzService .java
package com.movikr.svc.schedule.service.business;
import com.movikr.svc.schedule.service.task.config.QuartzManager;
import com.movikr.v2.core.req.quartz.JobParam;
import com.movikr.v2.core.resp.quartz.JobResult;
import com.movikr.v2.utils.commons.UtilDate;
import org.quartz.*;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* USER: samson
* TIME: 2015-12-07 18:12
* COMMENT:
*/
@Service("schedule-service-QuartzService")
public class QuartzService {
@Resource(name = "schedule-service-QuartzManager")
private QuartzManager quartzManager;
/**
* 获取job数据 遍历job和trigger
*
* @return
*/
public List<JobResult> get() {
List<JobResult> results = null;
try{
Set<JobKey> jobs = quartzManager.getAllJobs();
if(jobs != null && jobs.size() > 0){
results = new ArrayList<JobResult>(jobs.size());
for(JobKey jobKey : jobs){
List<? extends Trigger> triggers = quartzManager.getJobTriggers(jobKey);
for (Trigger trigger : triggers) {
JobResult job = new JobResult();
JobDetail jobDetail = quartzManager.getJobDetail(jobKey);
job.setJobName(jobKey.getName());
job.setJobGroupName(jobKey.getGroup());
job.setJobTriggerName(trigger.getKey().getName());
TriggerKey triggerKey = trigger.getKey();
job.setJobTriggerGroupName(triggerKey.getGroup());
Trigger.TriggerState triggerState = quartzManager.getTriggerStatus(triggerKey);
job.setJobTriggerStatus(triggerState.name());
job.setJobDetail(trigger.getDescription());
job.setJobClass(jobDetail.getJobClass().getName());
job.setJobTriggerNextFireTime(UtilDate.date2String(trigger.getNextFireTime(), "yyyy-MM-dd HH:mm:ss"));
job.setJobTriggerStartTime(UtilDate.date2String(trigger.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
job.setJobTriggerPreviousFireTime(UtilDate.date2String(trigger.getPreviousFireTime(), "yyyy-MM-dd HH:mm:ss"));
String cronExpression = quartzManager.getCronExpression(trigger);
job.setJobCorExpression(cronExpression);
results.add(job);
}
}
}
}catch (SchedulerException e){
throw new RuntimeException(e) ;
}
return results;
}
/**
* 删除job
*
* @param jobName
* @param jobGroupName
*/
public void delete(String jobName, String jobGroupName){
try{
quartzManager.removeJob(jobName, jobGroupName);
}catch (SchedulerException e){
throw new RuntimeException(e) ;
}
}
/**
* 暂停job
*
* @param jobName
* @param jobGroupName
*/
public void pause(String jobName, String jobGroupName){
try{
quartzManager.pauseJob(jobName, jobGroupName);
}catch (SchedulerException e){
throw new RuntimeException(e) ;
}
}
/**
* 恢复job 同pause
*
* @param jobName
* @param jobGroupName
*/
public void resume(String jobName, String jobGroupName){
try{
quartzManager.resumeJob(jobName, jobGroupName);
}catch (SchedulerException e){
throw new RuntimeException(e) ;
}
}
/**
* 添加job 重复会异常
*
* @param param
*/
public void add(JobParam param) {
try{
quartzManager.addJobWithTrigger(param.getJobName(), param.getJobGroupName(),
param.getJobTriggerName(), param.getJobTriggerGroupName(),
param.getJobClass(), param.getJobCorExpression(), param.getJobDetail());
}catch (Exception e){
throw new RuntimeException(e) ;
}
}
/**
* 修改job 修改表达式
*
* @param triggerName
* @param triggerGroupName
* @param expression
*/
public void modifyExpression(String triggerName, String triggerGroupName, String expression) {
try{
quartzManager.modifyCornExpression(triggerName, triggerGroupName, expression);
}catch (SchedulerException e){
throw new RuntimeException(e) ;
}
}
/**
* 立即启动
* @param jobName
* @param jobGroupName
*/
public void startNow(String jobName, String jobGroupName, Serializable jobData){
try{
quartzManager.startJob(jobName, jobGroupName, jobData);
}catch (SchedulerException e){
throw new RuntimeException(e) ;
}
}
/**
* 清理所有
*
*/
public void clean() {
try{
quartzManager.clear();
}catch (SchedulerException e){
throw new RuntimeException(e) ;
}
}
/**
* 停止所有 关闭所有资源 线程 任何方法都不能调用
*
*/
public void stopAll() {
try{
quartzManager.shutdownJobs();
}catch (SchedulerException e){
throw new RuntimeException(e) ;
}
}
public Trigger getTrigger(String triggerName, String triggerGroupName) {
return quartzManager.getTriigger(new TriggerKey(triggerName, triggerGroupName));
}
}
sql:
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for `QRTZ_BLOB_TRIGGERS`
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_BLOB_TRIGGERS`;
CREATE TABLE `QRTZ_BLOB_TRIGGERS` (
`SCHED_NAME` varchar(120) COLLATE utf8_bin NOT NULL,
`TRIGGER_NAME` varchar(200) COLLATE utf8_bin NOT NULL,
`TRIGGER_GROUP` varchar(200) COLLATE utf8_bin NOT NULL,
`BLOB_DATA` blob,
PRIMARY KEY (`SCHED_NAME`,`TRIGGER_NAME`,`TRIGGER_GROUP`),
CONSTRAINT `QRTZ_BLOB_TRIGGERS_ibfk_1` FOREIGN KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) REFERENCES `QRTZ_TRIGGERS` (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Table structure for `QRTZ_CALENDARS`
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_CALENDARS`;
CREATE TABLE `QRTZ_CALENDARS` (
`SCHED_NAME` varchar(120) COLLATE utf8_bin NOT NULL,
`CALENDAR_NAME` varchar(200) COLLATE utf8_bin NOT NULL,
`CALENDAR` blob NOT NULL,
PRIMARY KEY (`SCHED_NAME`,`CALENDAR_NAME`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Table structure for `QRTZ_CRON_TRIGGERS`
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_CRON_TRIGGERS`;
CREATE TABLE `QRTZ_CRON_TRIGGERS` (
`SCHED_NAME` varchar(120) COLLATE utf8_bin NOT NULL,
`TRIGGER_NAME` varchar(200) COLLATE utf8_bin NOT NULL,
`TRIGGER_GROUP` varchar(200) COLLATE utf8_bin NOT NULL,
`CRON_EXPRESSION` varchar(200) COLLATE utf8_bin NOT NULL,
`TIME_ZONE_ID` varchar(80) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`SCHED_NAME`,`TRIGGER_NAME`,`TRIGGER_GROUP`),
CONSTRAINT `QRTZ_CRON_TRIGGERS_ibfk_1` FOREIGN KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) REFERENCES `QRTZ_TRIGGERS` (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Table structure for `QRTZ_FIRED_TRIGGERS`
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_FIRED_TRIGGERS`;
CREATE TABLE `QRTZ_FIRED_TRIGGERS` (
`SCHED_NAME` varchar(120) COLLATE utf8_bin NOT NULL,
`ENTRY_ID` varchar(95) COLLATE utf8_bin NOT NULL,
`TRIGGER_NAME` varchar(200) COLLATE utf8_bin NOT NULL,
`TRIGGER_GROUP` varchar(200) COLLATE utf8_bin NOT NULL,
`INSTANCE_NAME` varchar(200) COLLATE utf8_bin NOT NULL,
`FIRED_TIME` bigint(13) NOT NULL,
`SCHED_TIME` bigint(13) NOT NULL,
`PRIORITY` int(11) NOT NULL,
`STATE` varchar(16) COLLATE utf8_bin NOT NULL,
`JOB_NAME` varchar(200) COLLATE utf8_bin DEFAULT NULL,
`JOB_GROUP` varchar(200) COLLATE utf8_bin DEFAULT NULL,
`IS_NONCONCURRENT` varchar(1) COLLATE utf8_bin DEFAULT NULL,
`REQUESTS_RECOVERY` varchar(1) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`SCHED_NAME`,`ENTRY_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Table structure for `QRTZ_JOB_DETAILS`
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_JOB_DETAILS`;
CREATE TABLE `QRTZ_JOB_DETAILS` (
`SCHED_NAME` varchar(120) COLLATE utf8_bin NOT NULL,
`JOB_NAME` varchar(200) COLLATE utf8_bin NOT NULL,
`JOB_GROUP` varchar(200) COLLATE utf8_bin NOT NULL,
`DESCRIPTION` varchar(250) COLLATE utf8_bin DEFAULT NULL,
`JOB_CLASS_NAME` varchar(250) COLLATE utf8_bin NOT NULL,
`IS_DURABLE` varchar(1) COLLATE utf8_bin NOT NULL,
`IS_NONCONCURRENT` varchar(1) COLLATE utf8_bin NOT NULL,
`IS_UPDATE_DATA` varchar(1) COLLATE utf8_bin NOT NULL,
`REQUESTS_RECOVERY` varchar(1) COLLATE utf8_bin NOT NULL,
`JOB_DATA` blob,
PRIMARY KEY (`SCHED_NAME`,`JOB_NAME`,`JOB_GROUP`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Table structure for `QRTZ_LOCKS`
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_LOCKS`;
CREATE TABLE `QRTZ_LOCKS` (
`SCHED_NAME` varchar(120) COLLATE utf8_bin NOT NULL,
`LOCK_NAME` varchar(40) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`SCHED_NAME`,`LOCK_NAME`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Table structure for `QRTZ_PAUSED_TRIGGER_GRPS`
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_PAUSED_TRIGGER_GRPS`;
CREATE TABLE `QRTZ_PAUSED_TRIGGER_GRPS` (
`SCHED_NAME` varchar(120) COLLATE utf8_bin NOT NULL,
`TRIGGER_GROUP` varchar(200) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`SCHED_NAME`,`TRIGGER_GROUP`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Table structure for `QRTZ_SCHEDULER_STATE`
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_SCHEDULER_STATE`;
CREATE TABLE `QRTZ_SCHEDULER_STATE` (
`SCHED_NAME` varchar(120) COLLATE utf8_bin NOT NULL,
`INSTANCE_NAME` varchar(200) COLLATE utf8_bin NOT NULL,
`LAST_CHECKIN_TIME` bigint(13) NOT NULL,
`CHECKIN_INTERVAL` bigint(13) NOT NULL,
PRIMARY KEY (`SCHED_NAME`,`INSTANCE_NAME`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Table structure for `QRTZ_SIMPLE_TRIGGERS`
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_SIMPLE_TRIGGERS`;
CREATE TABLE `QRTZ_SIMPLE_TRIGGERS` (
`SCHED_NAME` varchar(120) COLLATE utf8_bin NOT NULL,
`TRIGGER_NAME` varchar(200) COLLATE utf8_bin NOT NULL,
`TRIGGER_GROUP` varchar(200) COLLATE utf8_bin NOT NULL,
`REPEAT_COUNT` bigint(7) NOT NULL,
`REPEAT_INTERVAL` bigint(12) NOT NULL,
`TIMES_TRIGGERED` bigint(10) NOT NULL,
PRIMARY KEY (`SCHED_NAME`,`TRIGGER_NAME`,`TRIGGER_GROUP`),
CONSTRAINT `QRTZ_SIMPLE_TRIGGERS_ibfk_1` FOREIGN KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) REFERENCES `QRTZ_TRIGGERS` (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Table structure for `QRTZ_SIMPROP_TRIGGERS`
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_SIMPROP_TRIGGERS`;
CREATE TABLE `QRTZ_SIMPROP_TRIGGERS` (
`SCHED_NAME` varchar(120) COLLATE utf8_bin NOT NULL,
`TRIGGER_NAME` varchar(200) COLLATE utf8_bin NOT NULL,
`TRIGGER_GROUP` varchar(200) COLLATE utf8_bin NOT NULL,
`STR_PROP_1` varchar(512) COLLATE utf8_bin DEFAULT NULL,
`STR_PROP_2` varchar(512) COLLATE utf8_bin DEFAULT NULL,
`STR_PROP_3` varchar(512) COLLATE utf8_bin DEFAULT NULL,
`INT_PROP_1` int(11) DEFAULT NULL,
`INT_PROP_2` int(11) DEFAULT NULL,
`LONG_PROP_1` bigint(20) DEFAULT NULL,
`LONG_PROP_2` bigint(20) DEFAULT NULL,
`DEC_PROP_1` decimal(13,4) DEFAULT NULL,
`DEC_PROP_2` decimal(13,4) DEFAULT NULL,
`BOOL_PROP_1` varchar(1) COLLATE utf8_bin DEFAULT NULL,
`BOOL_PROP_2` varchar(1) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`SCHED_NAME`,`TRIGGER_NAME`,`TRIGGER_GROUP`),
CONSTRAINT `QRTZ_SIMPROP_TRIGGERS_ibfk_1` FOREIGN KEY (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`) REFERENCES `QRTZ_TRIGGERS` (`SCHED_NAME`, `TRIGGER_NAME`, `TRIGGER_GROUP`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Table structure for `QRTZ_TRIGGERS`
-- ----------------------------
DROP TABLE IF EXISTS `QRTZ_TRIGGERS`;
CREATE TABLE `QRTZ_TRIGGERS` (
`SCHED_NAME` varchar(120) COLLATE utf8_bin NOT NULL,
`TRIGGER_NAME` varchar(200) COLLATE utf8_bin NOT NULL,
`TRIGGER_GROUP` varchar(200) COLLATE utf8_bin NOT NULL,
`JOB_NAME` varchar(200) COLLATE utf8_bin NOT NULL,
`JOB_GROUP` varchar(200) COLLATE utf8_bin NOT NULL,
`DESCRIPTION` varchar(250) COLLATE utf8_bin DEFAULT NULL,
`NEXT_FIRE_TIME` bigint(13) DEFAULT NULL,
`PREV_FIRE_TIME` bigint(13) DEFAULT NULL,
`PRIORITY` int(11) DEFAULT NULL,
`TRIGGER_STATE` varchar(16) COLLATE utf8_bin NOT NULL,
`TRIGGER_TYPE` varchar(8) COLLATE utf8_bin NOT NULL,
`START_TIME` bigint(13) NOT NULL,
`END_TIME` bigint(13) DEFAULT NULL,
`CALENDAR_NAME` varchar(200) COLLATE utf8_bin DEFAULT NULL,
`MISFIRE_INSTR` smallint(2) DEFAULT NULL,
`JOB_DATA` blob,
PRIMARY KEY (`SCHED_NAME`,`TRIGGER_NAME`,`TRIGGER_GROUP`),
KEY `SCHED_NAME` (`SCHED_NAME`,`JOB_NAME`,`JOB_GROUP`),
CONSTRAINT `QRTZ_TRIGGERS_ibfk_1` FOREIGN KEY (`SCHED_NAME`, `JOB_NAME`, `JOB_GROUP`) REFERENCES `QRTZ_JOB_DETAILS` (`SCHED_NAME`, `JOB_NAME`, `JOB_GROUP`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
SET FOREIGN_KEY_CHECKS = 1;