因项目需要,需要在Web App中定期执行某Java程序。在Google上搜索发现了Quartz。
创建一个Job
第一步需要创建一个Job实现org.quartz.Job接口的execute方法。每次scheduler到点调用的就是这个程序。
package com.enix.dataxfer.scheduler;import org.quartz.DisallowConcurrentExecution;import org.quartz.Job;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import com.enix.dataxfer.jython.Transfer;@DisallowConcurrentExecutionpublic class TransferJob implements Job{ @Override public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("Transfer job is started..."); Transfer.batch(); System.out.println("Transfer job is ended..."); }}
2. 创建配置文件quartz.properties
配置文件quartz.properties需要放在WEB-INF/classes下,此处需要注意的是,
org.quartz.plugin.joinInitializer.fileName 指定步骤一创建的job的cron trigger信息,也就是说该Job多久运行一次。
jobs.xml也需要放在WEB-INF/classes文件夹下。
org.quartz.scheduler.instanceName = MyScheduler org.quartz.threadPool.threadCount = 1 org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.XMLSchedulingDataProcessorPlugin org.quartz.plugin.jobInitializer.fileNames = jobs.xml org.quartz.plugin.jobInitializer.failOnFileNotFound = true org.quartz.plugin.jobInitializer.scanInterval = 10 org.quartz.plugin.jobInitializer.wrapInUserTransaction = false
3. 创建jobs.xml定义步骤1创建的TransferJob
此处定义了一个cron trigger,从0:00开始,每隔5分钟触发一次TransferJob。对应的语法,大家可以参看
TransferJob DataBatchJobs Trigger the data migration script com.enix.dataxfer.scheduler.TransferJob TransferTrigger TransferJob DataBatchJobs 0 0/5 0-23 * * ?
4. 添加Listener到web.xml
最后一步,也就是要添加Quartz的listener到web.xml,这样JBOSS就会注册该listener,而定期执行任务。
org.quartz.ee.servlet.QuartzInitializerListener jfinal com.jfinal.core.JFinalFilter configClass com.enix.dataxfer.core.AppConfig jfinal /*
5. 部署程序,并查看运行日志
17:40:00,001 INFO [stdout] (MyScheduler_Worker-1) Transfer job is started...17:40:01,360 INFO [stdout] (MyScheduler_Worker-1) Transfer job is ended...17:45:00,002 INFO [stdout] (MyScheduler_Worker-1) Transfer job is started...17:45:01,367 INFO [stdout] (MyScheduler_Worker-1) Transfer job is ended...17:55:00,001 INFO [stdout] (MyScheduler_Worker-1) Transfer job is started...17:55:01,340 INFO [stdout] (MyScheduler_Worker-1) Transfer job is ended...