MethodInvokingJobDetailFactoryBean
CronTriggerBean
SchedulerFactoryBean
package com.xy.utils.quartz;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 测试定时器类
* @author javaw
*
*/
public class TestQuartz {
public static Logger logger = LoggerFactory.getLogger(TestQuartz.class);
public void TestMethod(){
logger.info("Auto Execute TestMethod start! Date={}" ,new DateTime().toString("YYYY-MM-DD HH:mm:ss" ));
logger.info("**********测试跑批类************");
logger.info("Auto Execute TestMethod end! Date={}" ,new DateTime().toString("YYYY-MM-DD HH:mm:ss" ));
}
}
public static void main(String[] args) {
SchedulerFactoryBean schedulerFactoryBean = (SchedulerFactoryBean) SpringUtilsFromClassPathXml.getBean( "testSchedulerFactoryBean");
//启动调度器
schedulerFactoryBean.start();
}
package com.xy.utils.quartz;
import org.joda.time.DateTime;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
/**
* 测试继承QuartzJobBean的java类配置定时器
* @author javaw
*
*/
public class TestQuartzExtendsJobBean extends QuartzJobBean{
private static Logger logger = LoggerFactory.getLogger(TestQuartzExtendsJobBean. class);
@Override
protected void executeInternal(JobExecutionContext context)
throws JobExecutionException {
logger.info("Auto Execute TestQuartzExtendsJobBean start! Date={}",new DateTime().toString( "YYYY-MM-DD HH:mm:ss"));
logger.info("**********"+content.getMergedJobDataMap().get("descString")+"************");
logger.info("Auto Execute TestQuartzExtendsJobBean end! Date={}",new DateTime().toString( "YYYY-MM-DD HH:mm:ss"));
}
}
集群部署定时器通过故障切换和负载均衡的功能,提高调度器的可用性和扩展性。
集群上的所有节点通过共享一个数据库来来工作的。所有节点quartz通过启动两个维护线程来维护数据库状态实现集群管理,一个是检测节点状态线程,一个是恢复任务线程。一个 Quartz 集群中的每个节点是一个独立的 Quartz 应用,它又管理着其他的节点。
负载均衡是自动完成的,集群的每个节点会尽快触发任务。当第一个节点获取到任务,会通过锁定,阻止其他线程获取到该任务。
当一个节点执行任务失败(服务down掉或其他原因),其他节点会检测到并标识在失败节点上正在执行的数据库中的任务。任何标记为可恢复(任务详细里的requests recovery属性)的任务都会被其他节点继续执行。没有标记可恢复的任务会被释放掉。
CREATE TABLE qrtz_job_details
(
....
JOB_NAME VARCHAR2(80) NOT NULL,
JOB_GROUP VARCHAR2(80) NOT NULL,
REQUESTS_RECOVERY VARCHAR2(1) NOT NULL, --可恢复标记
);
SchedulerFactoryBean
JobDetail
Trigger
Job
将定时任务持久化可以解决分布式跑批的问题,避免服务器重启信息丢失。
定时任务定义需要实例化JobDetail和Trigger,然后使用Scheduler进行调度。这个需要使用到Quartz的jar包。
每个jar包创建任务的方式都不相同。具体需要查看官方api。
quartz2.2.1中给出的示例:
JobDetail job = newJob(MyJob.class)
.withIdentity("myJob")
.build();
Trigger trigger = newTrigger()
.withIdentity(triggerKey("myTrigger", "myTriggerGroup"))
.withSchedule(simpleSchedule()
.withIntervalInHours(1)
.repeatForever())
.startAt(futureDate(10, MINUTES))
.build();
scheduler.scheduleJob(job, trigger);
导入jar包后,写如下测试类:
package com.xy.utils.scheduler;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
public class quartzTest {
public static void main(String args[]) throws Exception {
JobDetail jobDetail= JobBuilder.newJob(TestJob.class)
.withIdentity("job","group")
.build();
Trigger trigger= TriggerBuilder.newTrigger().withIdentity("job","group").startNow().withSchedule(
SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(10) //时间间隔
.withRepeatCount(10) //重复次数n+1
)
.build();
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
sched.scheduleJob(jobDetail, trigger);
sched.start();
}
}
定时执行的任务类:
package com.xy.utils.scheduler;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class TestJob implements Job {
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println("*****执行批处理任务******");
}
}
这种任务并没有持久化到数据库中。
下载了quartz.jar后,在\quartz-2.2.1\src\org\quartz\目录下有个quartz.properties的文件,可以根据自己的需要更改其中的配置内容。
#批处理常量表 QUARTZ2.2.1
#============================================================================
# Configure Main Scheduler Properties
#============================================================================
org.quartz.scheduler.instanceName = MyQuartzScheduler
org.quartz.scheduler.instanceId = AUTO
#============================================================================
# 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.misfireThreshold = 10000
org.quartz.jobStore.class = org.springframework.scheduling.quartz.LocalDataSourceJobStore
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.isClustered = true --是否集群部署
#任务表前缀
org.quartz.jobStore.tablePrefix = test_qrtz_
jar包文件中,给出了所有数据库的建表语句。可以根据给出的sql语句创建表。
package com.xy.utils.scheduler;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import com.xy.utils.SpringUtils.SpringUtilsFromClassPathXml;
public class quartzTest {
//从Spring中获取调度bean工厂
public static Scheduler scheduler = (Scheduler)SpringUtilsFromClassPathXml.getBean("schedulerBeanFactory");
public static void main(String args[]) throws Exception {
JobDetail jobDetail= JobBuilder.newJob(TestJob.class)
.withIdentity("job","group")
.build();
Trigger trigger= TriggerBuilder.newTrigger().withIdentity("job","group").startNow().withSchedule(
SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(10) //时间间隔
.repeatForever()
)
.build();
scheduler.scheduleJob(jobDetail, trigger);
scheduler.start();
}
}
package com.xy.utils.scheduler;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class TestJob implements Job {
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println("*****执行批处理任务******");
}
}
此时执行该类就会将任务数据写入数据库中。
自定义任务调度工具类:
package com.xy.utils.scheduler;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.DateBuilder;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.DateBuilder.IntervalUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.xy.common.SysContent;
public class SchedulerJobUtils {
private static Logger logger = LoggerFactory.getLogger(SchedulerJobUtils.class);
public static Scheduler scheduler = (Scheduler)SysContent.applicationContext.getBean("schedulerBeanFactory");
//public static Scheduler scheduler = (Scheduler)SpringUtilsFromClassPathXml.getBean("schedulerBeanFactory");
public static String dateFormate = "ss mm HH dd MM ? yyyy";
public static SimpleDateFormat cronSdf = new SimpleDateFormat(dateFormate);
public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* 数据库放入一个指定时间的任务,任务只执行一次
* @see 适合对数据进行定时删除,修改等等
* @param
* @param clazz 要执行任务类class,任务类必须继承Job类
* @param jobName 任务名称
* @param groupName 分组名称
* @param executeTime 执行时间,格式:yyyy-MM-dd HH:mm:ss
* @return
*/
public static boolean putSpecifyTimeSchedulerJobToDB(Class extends Job> clazz,String jobName,String groupName,String executeTime){
//定义一个job
JobDetail job = JobBuilder.newJob(clazz).withIdentity(jobName, groupName).build();
//定义一个TriggerKey
TriggerKey triggerKey = TriggerKey.triggerKey(jobName, groupName);
SchedulerJob schedulerJob = new SchedulerJob();
schedulerJob.setJobName(jobName);
schedulerJob.setGroupName(groupName);
job.getJobDataMap().put("schedulerJob", schedulerJob);
Date executeDate = null;
try {
executeDate = sdf.parse(executeTime);
} catch (ParseException e) {
logger.info("method putSchedulerJobToDB execute error!exception={}",e);
}
String dbExecuteTime = cronSdf.format(executeDate);
CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(CronScheduleBuilder.cronSchedule(dbExecuteTime)).build();
try {
scheduler.scheduleJob(job, cronTrigger);
} catch (SchedulerException e) {
logger.info("method putSchedulerJobToDB execute error!exception={}",e);
}
return true;
}
/**
* 数据库放入一条指定开始时间,指定间隔时间,指定次数的任务
* @param
* @param clazz 任务类
* @param jobName 任务名
* @param groupName 分组名
* @param seconds 间隔时间,以秒为单位
* @param count 执行次数,0为一直执行
* @param startSecondsToNow 开始时间(距离现在?秒)
* @return
* @throws SchedulerException
*/
@SuppressWarnings("unchecked")
public static boolean putPeriodSchedulerJobToDB(Class extends Job> clazz,String jobName,String groupName,
int seconds,int count,int startSecondsToNow){
JobDetail jobDetail= JobBuilder.newJob(clazz).withIdentity(jobName,groupName).build();
TriggerBuilder triggerBuilder = TriggerBuilder.newTrigger().withIdentity(jobName,groupName);
if(startSecondsToNow==0){
triggerBuilder.startNow();
}else{
triggerBuilder.startAt(DateBuilder.futureDate(startSecondsToNow,IntervalUnit.SECOND));
}
SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(seconds);
if(count==0){
scheduleBuilder.repeatForever();
}else{
scheduleBuilder.withRepeatCount(count);
}
Trigger trigger = triggerBuilder.withSchedule(scheduleBuilder).build();
try {
scheduler.scheduleJob(jobDetail,trigger);
} catch (SchedulerException e) {
logger.info("put putPeriodSchedulerJobToDB error,error={}",e);
}
return true;
}
}
任务类:
package com.xy.utils.scheduler;
import org.joda.time.DateTime;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestSchedulerTask implements Job{
private static Logger logger = LoggerFactory.getLogger(TestSchedulerTask.class);
public void execute(JobExecutionContext context) throws JobExecutionException {
logger.info("**********TestSchedulerTask1 start at={}",new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
logger.info("**********I'm Ok!************");
logger.info("**********TestSchedulerTask1 end at={}",new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
}
/**
* 调度任务工具类测试
* 10秒执行一次,无限次数,30秒后开始
* @param args
*/
public static void main(String[] args) {
System.out.println(SchedulerJobUtils.putPeriodSchedulerJobToDB(TestSchedulerTask.class, "myJob", "myGroup", 10, 0, 30));
}
}
数据库里的任务表:
打印出的日志:
2016-01-10 00:37:34,810 INFO TestSchedulerTask1:14 - **********TestSchedulerTask1 start at=2016-01-10 00:37:34
2016-01-10 00:37:34,810 INFO TestSchedulerTask1:15 - **********I'm Ok!************
2016-01-10 00:37:34,811 INFO TestSchedulerTask1:16 - **********TestSchedulerTask1 end at=2016-01-10 00:37:34
2016-01-10 00:37:44,690 INFO TestSchedulerTask1:14 - **********TestSchedulerTask1 start at=2016-01-10 00:37:44
2016-01-10 00:37:44,691 INFO TestSchedulerTask1:15 - **********I'm Ok!************
2016-01-10 00:37:44,691 INFO TestSchedulerTask1:16 - **********TestSchedulerTask1 end at=2016-01-10 00:37:44
2016-01-10 00:37:54,697 INFO TestSchedulerTask1:14 - **********TestSchedulerTask1 start at=2016-01-10 00:37:54
2016-01-10 00:37:54,697 INFO TestSchedulerTask1:15 - **********I'm Ok!************
2016-01-10 00:37:54,697 INFO TestSchedulerTask1:16 - **********TestSchedulerTask1 end at=2016-01-10 00:37:54