您的位置:首页 > 其它

Quartz任务调度的使用(lp)

2007-12-26 10:06 751 查看
Quartz任务调度的使用
这边的例子是使用Quartz任务调度定时将一个数据库的表拷贝到另一个数据库。
一、配置
下载quartz相关的.jar包,放在工程下的lib文件夹下,并添加到工程中。
如果涉及到日志的输出,必须还要有日志的配置文件,也要放在工程下。如log4j.xml或者log4j.propertis,配置文件copy一个就可以了。

二、新建一个带main()方法的类。
如:MainClass.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SchedulerMetaData;
import org.quartz.impl.StdSchedulerFactory;

public class MainClass {
public void run() throws Exception {

// First we must get a reference to a scheduler
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
sched.start();

// wait five minutes to give our jobs a chance to run
try {
Thread.sleep(900L * 1000L);
} catch (Exception e) {
}

// shut down the scheduler
sched.shutdown(true);
}

public static void main(String[] args) throws Exception {
MainClass mainClass = new MainClass();
mainClass.run();
}
}

三、 配置quartz.propertis
这里的org.quartz.plugin.jobInitializer.fileNames = jobs.xml是标明任务的文件。
quartz.propertis全文:
#=================================================================
# Configure Main Scheduler Properties
#=================================================================
org.quartz.scheduler.instanceName = TestScheduler
org.quartz.scheduler.instanceId = AUTO

#=================================================================
# Configure ThreadPool
#=================================================================
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 3
org.quartz.threadPool.threadPriority = 5

#=================================================================
# Configure JobStore
#=================================================================
org.quartz.jobStore.misfireThreshold = 60000
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore

#org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
#org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.PostgreSQLDelegate
#org.quartz.jobStore.useProperties = false
#org.quartz.jobStore.dataSource = myDS
#org.quartz.jobStore.tablePrefix = QRTZ_
#org.quartz.jobStore.isClustered = false

#=================================================================
# Configure Datasources
#=================================================================
#org.quartz.dataSource.myDS.driver = org.postgresql.Driver
#org.quartz.dataSource.myDS.URL = jdbc:postgresql://localhost/dev
#org.quartz.dataSource.myDS.user = jhouse
#org.quartz.dataSource.myDS.password =
#org.quartz.dataSource.myDS.maxConnections = 5

#=================================================================
# Configure Plugins
#=================================================================
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 = jobs.xml
org.quartz.plugin.jobInitializer.overWriteExistingJobs = true
org.quartz.plugin.jobInitializer.failOnFileNotFound = true
org.quartz.plugin.jobInitializer.scanInterval = 10
org.quartz.plugin.jobInitializer.wrapInUserTransaction = false

四、配置jobs.xml
解释1:<job-data-map> ....</job-data-map>是传给SimpleJob.java的各种参数,在SimpleJob.java中我们可以用jobExecutionContext.getJobDetail()
<?xml version='1.0' encoding='utf-8'?>
<quartz xmlns="http://www.opensymphony.com/quartz/JobSchedulingData"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.opensymphony.com/quartz/JobSchedulingData http://www.opensymphony.com/quartz/xml/job_scheduling_data_1_5.xsd" version="1.5">
<calendar class-name="org.quartz.impl.calendar.HolidayCalendar" replace="true">
<name>holidayCalendar</name>
<description>HolidayCalendar</description>
<base-calendar class-name="org.quartz.impl.calendar.WeeklyCalendar">
<name>weeklyCalendar</name>
<description>WeeklyCalendar</description>
<base-calendar class-name="org.quartz.impl.calendar.AnnualCalendar">
<name>annualCalendar</name>
<description>AnnualCalendar</description>
</base-calendar>
</base-calendar>
</calendar>
<job>
<job-detail>
<name>testJob1</name>
<group>testJobs</group>
<description>Test Job Number 1</description>
<job-class>SimpleJob</job-class>
<volatility>false</volatility>
<durability>false</durability>
<recover>false</recover>
<job-data-map>
<entry>
<key>sourceUrl</key>
<value>jdbc:mysql://localhost:3306/test</value>
</entry>
<entry>
<key>sourceUser</key>
<value>root</value>
</entry>
<entry>
<key>sourcePassword</key>
<value>123456</value>
</entry>
<entry>
<key>targetUrl</key>
<value>jdbc:mysql://localhost:3306/target</value>
</entry>
<entry>
<key>targetUser</key>
<value>root</value>
</entry>
<entry>
<key>targetPassword</key>
<value>123456</value>
</entry>
<entry>
<key>tableName</key>
<value>User</value>
</entry>
</job-data-map>
</job-detail>
<trigger>
<cron>
<name>testTrigger1</name>
<group>testJobs</group>
<description>Test Trigger Number 1</description>
<job-name>testJob1</job-name>
<job-group>testJobs</job-group>
<cron-expression> 0 0/1 * * * ?</cron-expression>
</cron>
</trigger>
</job>
</quartz>

五、SimpleJob.java
继承org.quartz..Job接口,自动执行execute方法。
import java.sql.*;
import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.*;

public class SimpleJob implements Job {
public SimpleJob() {
}
public void execute(JobExecutionContext jobExecutionContext)
throws JobExecutionException {
JobDataMap jobDataMap = jobExecutionContext.getJobDetail()
.getJobDataMap();

String sourceUrl = jobDataMap.getString("sourceUrl");
String sourceUser = jobDataMap.getString("sourceUser");
String sourcePassword = jobDataMap.getString("sourcePassword");
String targetUrl = jobDataMap.getString("targetUrl");
String targetUser = jobDataMap.getString("targetUser");
String targetPassword = jobDataMap.getString("targetPassword");
String tableName = jobDataMap.getString("tableName");
try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
Connection connA = DriverManager.getConnection(sourceUrl,
sourceUser, sourcePassword);
Connection connB = DriverManager.getConnection(targetUrl,
targetUser, targetPassword);

ExchangeDAO.importData(tableName, connA, connB);
//这是把表从一个数据源拷贝到另一个数据源的函数。详见下一篇的文章。

} catch (Exception e) {
e.printStackTrace();
}
}
}

.getJobDataMap.getString("kye");来获取他的value值。
解释2:"Cron-Expression"由6到7个用空格分开的字段组成的表达式这6或7个字段必须遵循下面的顺序和格式:
Seconds 0-59 , - * /
Minutes 0-59 ,- * /
Hours 0-23 , - * /
Day-of-month 1-31 , - * ? / L W C
Month 1-12 or JAN-DEC , - * /
Day-of-Week 1-7 or SUN-SAT , - * ? / L C #
Year (Optional) empty, 1970-2099 , - * /
*是一个通配符,表示任何值,用在Minutes字段中表示每分钟。
?只可以用在day-of-month或者Day-of-Week字段中,用来表示不指定特殊的值。
-用来表示一个范围,比如10-12用在Month中表示10到12月。
,用来表示附加的值,比如MON,WED,FRI在day-of-week字段中表示礼拜一和礼拜三和礼拜五。
/用来表示增量,比如0/15用在Minutes字段中表示从0分开始0和15和30和45分。
L只可以用在day-of-month或者Day-of-Week字段中,如果用在Day-of-month中,表示某个月的最后一天,1月则是表示31号,2月则表示28号(非闰年),如果用在Day-of-Week中表示礼拜六(数字7);但是如果L与数字组合在一起用在Day-of-month中,比如6L,则表示某个月的最后一个礼拜六;
C
W
#

0 1 0 1 1-12 ?表示每月1号0点1分执行。
0 0 21 ? * 1表示每个礼拜天 21点0分执行。
0 0 0 * * ?表示每天0点0分执行。
0 * 22 * * ?表示每天22点开始每分钟
0 * 0-23 * * ?表示每天每分钟

jobs.xml全文:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: