用quartz可以实现web或非web模式的定时器
1、配置文件
quartz_job.xml
- xml version="1.0" encoding="UTF-8"?>
- <quartz xmlns="http://www.opensymphony.com/quartz/JobSchedulingData"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- overwrite-existing-jobs="true">
- <job>
- <job-detail>
- <name>yayaittname>
- <group>CRAWLER_JOB_GROUPgroup>
- <description>send task per daydescription>
- <job-class>com.yahaitt.quartz.QuartzSystemjob-class>
- <job-data-map allows-transient-data="true">
- <entry>
- <key>usernamekey>
- <value>wujinlivalue>
- entry>
- <entry>
- <key>passwordkey>
- <value>mahaibovalue>
- entry>
- job-data-map>
- job-detail>
- <trigger>
- <cron>
- <name>hourTaskJob-triggername>
- <group>CRAWLER_TRIGGER_GROUPgroup>
- <job-name>yayaittjob-name>
- <job-group>CRAWLER_JOB_GROUPjob-group>
- <cron-expression>1/12 * * * * ?cron-expression>
- cron>
- trigger>
- job>
- quartz>
该定时器实现了每12秒触发类com.yahaitt.quartz.QuartzSystem的execute函数,并通过java-data-map标签来实现参数的传递,如果不需要传递参数,可以将整个java-data-map标签去除。
需要注意的是job-detail与trigger中各子标签间的关系,比如trigger中job-name和job-group要与job-detail中的name和group对应。
可以通过在quartz标签中添加多个job来实现多个定时器的管理。
2、定义org.quartz.Job接口的实现类
QuartzSystem.java
- package com.yahaitt.quartz;
- import org.quartz.Job;
- import org.quartz.JobExecutionContext;
- import org.quartz.JobExecutionException;
- public class QuartzSystem implements Job {
- public void execute(JobExecutionContext context) throws JobExecutionException {
- // TODO Auto-generated method stub
- String username = context.getJobDetail().getJobDataMap().getString("username");
- String password = context.getJobDetail().getJobDataMap().getString("password");
- System.out.println("username:" + username);
- System.out.println("password:" + password);
- }
- }
通过调用JobExecutionContext 的getJobDetail().getJobDataMap().getString(String paramname)来取得配置文件中定义的参数的值。
当定时器触发时,将执行该类的execute函数。
3、设置监听器
TaskScheduler.java
- package com.yahaitt.quartz;
- import java.util.Properties;
- import org.apache.log4j.Logger;
- import org.quartz.Scheduler;
- import org.quartz.SchedulerException;
- import org.quartz.SchedulerFactory;
- import org.quartz.impl.StdSchedulerFactory;
- import org.quartz.xml.JobSchedulingDataProcessor;
- public class TaskScheduler {
- // Logger
- private static Logger logger = Logger.getLogger(TaskScheduler.class);
- private static Scheduler scheduler;
- private String jobsConfigFile = "quartz-jobs.xml";
- public TaskScheduler() {
- initScheduler();
- }
- /**
- *
- * @param fileName
- * @return
- */
- public void initScheduler() {
- try {
- StdSchedulerFactory factory = new StdSchedulerFactory();
- //
- Properties properties = new Properties();
- properties.put("org.quartz.scheduler.instanceName","DefaultQuartzScheduler");
- properties.put("org.quartz.scheduler.rmi.export","false");
- properties.put("org.quartz.scheduler.rmi.proxy","false");
- properties.put("org.quartz.scheduler.wrapJobExecutionInUserTransaction","false");
- properties.put("org.quartz.threadPool.class","org.quartz.simpl.SimpleThreadPool");
- properties.put("org.quartz.threadPool.threadCount","20");
- properties.put("org.quartz.threadPool.threadPriority","5");
- properties.put("org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread","true");
- properties.put("org.quartz.jobStore.misfireThreshold","60000");
- properties.put("org.quartz.jobStore.class","org.quartz.simpl.RAMJobStore");
- // org.quartz.plugin.jobInitializer.validating = false
- // org.quartz.plugin.jobInitializer.validatingSchema = false
- // org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.JobInitializationPlugin
- // org.quartz.plugin.jobInitializer.fileName = quartz-jobs.xml
- // org.quartz.plugin.jobInitializer.overWriteExistingJobs = false
- // org.quartz.plugin.jobInitializer.failOnFileNotFound = true
- factory.initialize(properties);
- SchedulerFactory sf = (StdSchedulerFactory)factory;
- scheduler = sf.getScheduler();
- //Placing a Scheduler in Stand-by Mode
- //scheduler.standby();
- } catch (SchedulerException e) {
- e.printStackTrace();
- logger.error(e);
- }
- }
- /**
- * 从指定的任务配置文件中初始化计划任务
- * @param jobsConfig
- * @throws Exception
- */
- public void initJobs(String jobsConfig) throws Exception {
- //
- this.jobsConfigFile = jobsConfig;
- //
- JobSchedulingDataProcessor xmlProcessor = new JobSchedulingDataProcessor();
- //the last parameter here (the boolean one)is for overwriting existing jobs
- xmlProcessor.processFileAndScheduleJobs(jobsConfigFile, scheduler, true);
- }
- /**
- * 开启计划任务
- * @throws SchedulerException
- */
- public void startScheduler() throws SchedulerException {
- // Scheduler will not execute jobs until it has been started (though they can be scheduled before start())
- scheduler.start();
- }
- /**
- * 停止计划任务
- * @throws SchedulerException
- */
- public void shutdownScheduler() throws SchedulerException {
- scheduler.shutdown();
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- String jobsConfigfile = "E:/workspace/crawler/conf/quartz_job.xml";
- TaskScheduler scheduler = new TaskScheduler();
- try {
- scheduler.initJobs(jobsConfigfile);
- scheduler.startScheduler();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }