quartz是一个完全由java编写的作业调度管理的一个轻量级框架,目前在很多企业应用中被使用,类似于java类库中的TimeTask、数据库中的job等。但quartz功能更强大、更灵活。相应的jar包可以到开源网站里去下载,这里我们直接从建一个quartz_demo工程开始,做一个入门实例。(本文章没做具体叙述,详细内容请参看本人其他博文)
工程目录结构图:
一、新建一个java工程quartz_demo,引入quartz的jar包以及第三方包在quartzxxx/lib目录下。
二、创建一个job类,该job类功能为扫描某一个目录,统计该目录下xml文件的信息。
job类要实现org.quartz.Job接口,其中的execute方法就是用来执行job的业务逻辑的。
package com.gyb; import java.io.File; import java.io.FilenameFilter; import org.quartz.Job; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; /** * @Title: ScanDirJob.java * @Package: com.gyb * @Desc: 扫描文件目录信息 * @Copyright: AsiaInfo-Linkage * @author: gaoyb * @date: Mar 31, 2012 9:48:15 AM * @Email: [email protected] */ public class ScanDirJob implements Job { public void execute(JobExecutionContext context) throws JobExecutionException { JobDataMap dataMap = context.getMergedJobDataMap(); String dirName = dataMap.getString("SCAN_DIR"); if(dirName == null){ throw new JobExecutionException("Directory not configured"); } File fileDir = new File(dirName); if(!fileDir.exists()){ throw new JobExecutionException("Invalid Dir: " + dirName); } //get only xml files File [] files = fileDir.listFiles(new FilenameFilter(){ public boolean accept(File dir, String name) { name = name.toLowerCase(); return name.endsWith(".xml"); } }); if(files == null || files.length <= 0){ System.out.println("No xml found id dir: " + dirName); return; } //the number of xml files int size = files.length; for(int i=0; i<size; i++){ File file = files[i]; File afile = file.getAbsoluteFile(); long fileSize = file.length(); String msg = afile + "--size:" +fileSize; System.out.println(msg); } } }
三、创建作业管理器类JobScheduler来启动作业
package com.gyb; import java.util.Date; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.impl.StdSchedulerFactory; /** * @Title: JobScheduler.java * @Package: com.gyb * @Desc: job 调度器 * @Copyright: AsiaInfo-Linkage * @author: gaoyb * @date: Mar 31, 2012 10:38:33 AM * @Email: [email protected] */ public class JobScheduler { public static void main(String args[]) throws SchedulerException{ JobScheduler jobScheduler = new JobScheduler(); jobScheduler.startScheduler(); } public void startScheduler() throws SchedulerException{ Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); System.out.println("scheduler: " + scheduler); scheduler.start(); System.out.println("Scheduler started at "+ new Date()); } }
四、配置quartz.properties,这个在框架的org.quartz下也有一个,框架默认会去classpath下加载这个文件。
这个文件主要是对scheduler、threadPool、jobStore、plugin等这几块进行配置。
这里指定了job配置的xml文件目录:
org.quartz.plugin.jobInitializer.fileNames = my_quartz_jobs.xml
可以配置多个xml文件,已逗号隔开,比如:
org.quartz.plugin.jobInitializer.fileNames = my_quartz_jobs.xml,my_quartz_jobs2.xml
# Default Properties file for use by StdSchedulerFactory # to create a Quartz Scheduler Instance, if a different # properties file is not explicitly specified. # #config scheduler 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 #config threadPool org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool org.quartz.threadPool.threadCount = 10 org.quartz.threadPool.threadPriority = 5 org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true #config jobStore org.quartz.jobStore.misfireThreshold = 600000 org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore #config plugin org.quartz.plugin.triggHistory.class = org.quartz.plugins.history.LoggingJobHistoryPlugin org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.JobInitializationPlugin org.quartz.plugin.jobInitializer.fileNames = my_quartz_jobs.xml org.quartz.plugin.jobInitializer.overWriteExistingJobs = true org.quartz.plugin.jobInitializer.validating = false org.quartz.plugin.jobInitializer.overWriteExistingJobs = false org.quartz.plugin.jobInitializer.failOnFileNotFound = true
五、新建配置job详细信息的xml文件my_quartz_jobs.xml,在框架中默认会去加载quartz_jobs.xml。我们可以定义自己命名的xml文件。可以定义多个。
每个xml里可以定义多个job,下面例子中配置的触发器从2012-03-31T05:55:00开始每隔3秒执行一次。
<?xml version="1.0" encoding="UTF-8"?> <quartz> <job> <job-detail> <name>ScanDirJob</name> <group>DEFAULT</group> <description> A job that scans a directory for files </description> <job-class> com.gyb.ScanDirJob </job-class> <volatility>false</volatility> <durability>false</durability> <recover>false</recover> <job-data-map allows-transient-data="true"> <entry> <key>SCAN_DIR</key> <value>D:\workspace\resmanm_qhai\web\WEB-INF</value> </entry> </job-data-map> </job-detail> <trigger> <simple> <name>scanTrigger1</name> <group>DEFAULT</group> <job-name>ScanDirJob</job-name> <job-group>DEFAULT</job-group> <start-time>2012-03-31T05:55:00</start-time> <end-time>2012-03-31T06:00:00</end-time> <!-- repeat indefinitely every 3 seconds --> <repeat-count>-1</repeat-count> <repeat-interval>3000</repeat-interval> </simple> </trigger> </job> </quartz>
六、运行JobScheduler类,效果如下: