Quartz使用

本文详细介绍了如何在项目中配置Quartz定时任务,包括pom.xml依赖引入、spring配置文件设置及具体定时任务实现。通过实例演示了定时任务如何从SQL Server数据库同步数据到本地库,并进行数据统计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.pom.xml文件

<!-- quartz定时器 -->
<dependency>
	<groupId>org.quartz-scheduler</groupId>
	<artifactId>quartz</artifactId>
	<version>2.2.3</version>
</dependency>

2.spring配置文件中加入quartz的配置文件

<!-- 定时任务配置文件 -->
<import resource="quartz-task.xml"/>

3.quartz配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans      
    http://www.springframework.org/schema/beans/spring-beans.xsd   
    http://www.springframework.org/schema/util  
    http://www.springframework.org/schema/util/spring-util.xsd">
	<!-- job的配置开始 -->
	<bean id="myQuartzJobDetail"
		class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
		<property name="jobClass" value="com.centit.timer.MyQuartzJob" />
	</bean>
	
	<bean id="shipCountJobDetail"
		class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
		<property name="jobClass" value="com.centit.timer.ShipCountJob" />
	</bean>

	<bean id="rsh_simpleTrigger1" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
		<property name="jobDetail" ref="myQuartzJobDetail" />
		<property name="startDelay" value="500" />
		<property name="repeatInterval" value="0" />
		<property name="repeatCount" value="0" />
	</bean>

	<!--  job的配置结束 -->
	<!--  调度任务配置开始 -->
	<bean id="cronTestQuartzJobTrigger"
		class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
		<property name="jobDetail" ref="myQuartzJobDetail" />
		<!--  每个整点执行一次 -->
		<!-- <property name="cronExpression" value="0 0 0/1 * * ?" /> -->
		<property name="cronExpression" value="0 0/30 * * * ?" />
	</bean>
	
	<bean id="shipCountTrigger"
		class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
		<property name="jobDetail" ref="shipCountJobDetail" />
		<!--  每天凌晨1点执行一次 -->
		<property name="cronExpression" value="0 0 1 * * ?" />
	</bean>

	<!-- 启动工作 &ndash;&gt;
	<bean id="startQuertz" lazy-init="false" 
		class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="triggers">
			<list>
				<!--  这里添加多个定时任务触发器,对应第2步的bean id -->
				<ref bean="cronTestQuartzJobTrigger" />
				<ref bean="shipCountTrigger" />
				<ref bean="rsh_simpleTrigger1" />
			</list>
		</property>
	</bean>-->
</beans> 
package com.centit.timer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.centit.timer.service.SchedulejobManager;
import com.centit.timer.util.SpringBeanFactoryUtils;

public class MyQuartzJob implements Job {
	
	public static final Log log = LogFactory.getLog(MyQuartzJob.class);
	
	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		// TODO Auto-generated method stub
		System.out.println("********定时任务开始********");
		SchedulejobManager schedulejobMag = SpringBeanFactoryUtils.getBean("schedulejobManagerImpl");
    	schedulejobMag.autoTest();
	}

}
package com.centit.timer.service.impl;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.centit.framework.hibernate.dao.DatabaseOptUtils;
import com.centit.framework.hibernate.dao.SysDaoOptUtils;
import com.centit.ship.dao.ShipcountDao;
import com.centit.ship.dao.ShipmentDao;
import com.centit.ship.po.Shipcount;
import com.centit.ship.po.Shipment;
import com.centit.ship.service.ShipcountManager;
import com.centit.ship.service.ShipmentManager;
import com.centit.timer.dbsql.DBConnection;
import com.centit.timer.service.SchedulejobManager;
import com.centit.timer.util.DateUtil;

@Service
@Transactional(readOnly=false)
public class SchedulejobManagerImpl implements SchedulejobManager {
	
	@Resource
	private ShipmentManager shipmentManager;
	
	@Resource
	private ShipcountManager shipcountManager;
	
	@Resource
	private ShipcountDao ShipcountDao;
	
	@Transactional
	@Override
	public void autoTest() {
		System.out.println("*****同步数据开始(start):"+System.currentTimeMillis()+"*****");
		Connection con = null;
	   	Statement st = null;
	   	ResultSet rs = null;
	   	
		
		String checkintime = null;
		
		//获取库中最新时间
		checkintime = shipmentManager.getMaxCheckInTime();
		//System.out.println(checkintime);
		
		//当前时间的数据为空
		//checkintime = "2018-07-06 10:00:42";
		//初始化第一次库中没有数据
		if(StringUtils.isEmpty(checkintime)){
			StringBuffer sql = new StringBuffer();
			//前7天的数据(包括当天)
		   	sql.append("select t.sh_i_seq as seq,t.sh_ticketno as ticketno,t.sh_vehicletype as vehicletype,t.sh_weight as weight,t.sh_toll as toll,CONVERT(varchar(100),t.sh_checkintime, 20) as checkintime,");
		   	sql.append("t.sh_delflag as delflag,t.sh_dangers as dangers,t.sh_shipname as shipname,t.sh_peoplenumber as peoplenumber from t_shipment t ");
		   	sql.append("where 1=1 and DateDiff(dd,t.sh_checkintime, GETDATE()) < 7 order by t.sh_checkintime asc");
		   	
		   	try {
				con = DBConnection.getConnection();
				st = con.createStatement();
				rs = st.executeQuery(sql.toString());
				Shipment shipment = null;
				while (rs.next()) {
					shipment = new Shipment();
					shipment.setShCode(DateUtil.getUUID());
					shipment.setShISeq(rs.getString("seq"));
					shipment.setShTicketno(rs.getLong("ticketno"));
					shipment.setShVehicletype(String.valueOf(rs.getInt("vehicletype")));
					shipment.setShWeight((long)rs.getInt("weight"));
					shipment.setShToll((long) rs.getDouble("toll"));
					String checkintimess = rs.getString("checkintime");
					shipment.setShCheckintime(DateUtil.strToDateLong(rs.getString("checkintime")));
					shipment.setShDelflag(String.valueOf(rs.getInt("delflag")));
					shipment.setShDangers(String.valueOf(rs.getInt("dangers")));
					shipment.setShShipname(rs.getString("shipname"));
					shipment.setShPeoplenumber((long) rs.getInt("peoplenumber"));
					shipmentManager.saveNewObject(shipment);
				}

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (rs != null) {
						rs.close();
					}
					if (st != null) {
						st.close();
					}
					if (con != null) {
						con.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			} 
		   	
		}
		
		/**
		 * 库中有数据,根据最新的时间,获取sqlserver数据库中的数据;
		 * 条件:取大于等于(>=)最新时间的数据
		 */
		if(StringUtils.isNotEmpty(checkintime)){
			
			//获取db数据库中,最新时间的记录数,该时间点至少存在一条数据
			int count = shipmentManager.getCountForCheckInTime(checkintime);
			
			
			//获取sqlserver数据库中,最新时间对于的记录数
			StringBuffer sql_db = new StringBuffer();
			//前7天的数据(包括当天)
			sql_db.append(" select count(*) as num from t_shipment t ");
			sql_db.append(" where 1=1 and t.sh_checkintime = convert(datetime,'"+checkintime+"', 20) ");
			int num = 0;
			
			
			try {
				con = DBConnection.getConnection();
				st = con.createStatement();
				rs = st.executeQuery(sql_db.toString());
				if (rs.next()) {
					num = rs.getInt(1);
	            }
				
				//两边记录数不一致,删掉重新录入数据
				if(!(num == count)){
					
					//有数据执行删除操作
					if(count != 0 && num != 0){
						shipmentManager.deleteCountForCheckInTime(checkintime);
					}
					
					if(num != 0){
						//重新录入数据
						StringBuffer sql_db_2 = new StringBuffer();
						sql_db_2.append("select t.sh_i_seq as seq,t.sh_ticketno as ticketno,t.sh_vehicletype as vehicletype,t.sh_weight as weight,t.sh_toll as toll,CONVERT(varchar(100),t.sh_checkintime, 20) as checkintime,");
						sql_db_2.append("t.sh_delflag as delflag,t.sh_dangers as dangers,t.sh_shipname as shipname,t.sh_peoplenumber as peoplenumber from t_shipment t ");
						sql_db_2.append("where 1=1 and t.sh_checkintime = convert(datetime,'"+checkintime+"', 20) ");
						sql_db_2.append(" order by t.sh_checkintime asc");
						
						rs = st.executeQuery(sql_db_2.toString());
						Shipment shipment = null;
						while (rs.next()) {
							shipment = new Shipment();
							shipment.setShCode(DateUtil.getUUID());
							shipment.setShISeq(rs.getString("seq"));
							shipment.setShTicketno(rs.getLong("ticketno"));
							shipment.setShVehicletype(String.valueOf(rs.getInt("vehicletype")));
							shipment.setShWeight((long)rs.getInt("weight"));
							shipment.setShToll((long) rs.getDouble("toll"));
							String checkintimess = rs.getString("checkintime");
							shipment.setShCheckintime(DateUtil.strToDateLong(rs.getString("checkintime")));
							shipment.setShDelflag(String.valueOf(rs.getInt("delflag")));
							shipment.setShDangers(String.valueOf(rs.getInt("dangers")));
							shipment.setShShipname(rs.getString("shipname"));
							shipment.setShPeoplenumber((long) rs.getInt("peoplenumber"));
							shipmentManager.saveNewObject(shipment);
						}
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (rs != null) {
						rs.close();
					}
					if (st != null) {
						st.close();
					}
					if (con != null) {
						con.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			} 

			
			
			
			/**
			 * 根据最新的时间,获取sqlserver数据库中的数据
			 * 条件:sh_checkintime >checkintime(最新的时间)
			 * 测试时间:String checkintimetest = "2018-07-06 10:00:42";
			 */
			StringBuffer sql = new StringBuffer();
		   	sql.append("select t.sh_i_seq as seq,t.sh_ticketno as ticketno,t.sh_vehicletype as vehicletype,t.sh_weight as weight,t.sh_toll as toll,CONVERT(varchar(100),t.sh_checkintime, 20) as checkintime,");
		   	sql.append("t.sh_delflag as delflag,t.sh_dangers as dangers,t.sh_shipname as shipname,t.sh_peoplenumber as peoplenumber from t_shipment t ");
		   	sql.append("where 1=1 and t.sh_checkintime > convert(datetime,'"+checkintime+"', 20) ");
		   	sql.append(" order by t.sh_checkintime asc");
			
		   	try {
				con = DBConnection.getConnection();
				st = con.createStatement();
				rs = st.executeQuery(sql.toString());
				Shipment shipment = null;
				while (rs.next()) {
					shipment = new Shipment();
					shipment.setShCode(DateUtil.getUUID());
					shipment.setShISeq(rs.getString("seq"));
					shipment.setShTicketno(rs.getLong("ticketno"));
					shipment.setShVehicletype(String.valueOf(rs.getInt("vehicletype")));
					shipment.setShWeight((long)rs.getInt("weight"));
					shipment.setShToll((long) rs.getDouble("toll"));
					String checkintimess = rs.getString("checkintime");
					shipment.setShCheckintime(DateUtil.strToDateLong(rs.getString("checkintime")));
					shipment.setShDelflag(String.valueOf(rs.getInt("delflag")));
					shipment.setShDangers(String.valueOf(rs.getInt("dangers")));
					shipment.setShShipname(rs.getString("shipname"));
					shipment.setShPeoplenumber((long) rs.getInt("peoplenumber"));
					shipmentManager.saveNewObject(shipment);
				}

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (rs != null) {
						rs.close();
					}
					if (st != null) {
						st.close();
					}
					if (con != null) {
						con.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			} 
		}
		System.out.println("*****同步数据结束(end):"+System.currentTimeMillis()+"*****");
	}
	
	@Transactional
	@Override
	public void autoShipCount() {
		System.out.println("*****统计开始(statistics start):"+System.currentTimeMillis()+"*****");
		shipcountManager.getShipCount();
		System.out.println("*****统计结束(statistics end):"+System.currentTimeMillis()+"*****");
	}

}

 

<think>好的,我现在需要帮助用户了解Quartz使用方法或教程。首先,我得回忆一下Quartz的基本概念和主要功能。Quartz是一个开源的作业调度框架,用于在Java应用中执行定时任务。用户可能想了解如何配置、创建任务以及启动调度器。 根据用户提供的引用内容,引用[1]提到Quartz应用有时被称为服务器节点,这可能涉及集群配置。引用[2]指出任务类需要一个公共的空构造函数,这可能是在实现Job接口时需要注意的点。引用[3]提到任务需要实现org.quartz.Job接口,并实现execute()方法。这些都是关键点,需要在回答中涵盖。 接下来,我需要按照用户的系统级指令来组织回答。用户要求使用中文,正确使用LaTeX格式的行内和独立公式,生成相关问题,并在引用处添加标识。不过,在Quartz的教程中可能不太涉及数学公式,所以可能需要确认是否有必要添加。不过根据示例,用户可能接受在必要时使用,比如在配置参数或表达式时,如果有的话。例如,定时表达式可能需要说明,但Quartz通常使用cron表达式,可能不需要LaTeX数学公式,因此可能不需要特别处理这部分,但需要确保其他格式要求。 回答结构需要清晰,分步骤说明。可能需要包括配置Quartz、创建任务、配置调度器和触发器等步骤。同时,要引用提供的引用内容,确保在适当的地方添加引用标识。例如,在提到任务类需要空构造函数时,引用[2],在解释任务Job时引用[3]。 然后,需要生成相关问题。根据用户之前的示例,问题可能围绕配置、优化、应用场景等。例如,如何配置集群,如何处理任务异常,Quartz的持久化配置等。 需要检查是否遗漏了重要步骤,比如依赖配置(如添加Quartz库到项目中),或者调度器的启动和关闭。此外,是否需要提到JobDataMap传递参数,触发器的类型(如SimpleTrigger和CronTrigger)等,都是Quartz教程中的常见内容。 最后,确保回答符合用户的要求:结构清晰,分步骤,引用正确,问题相关。需要避免使用Markdown格式,但用户提供的示例中使用了代码块,所以可能需要保留代码示例,但根据用户当前的指令,用户可见层可能允许代码块。需要确认用户是否允许代码块,但根据问题中的示例,用户似乎接受代码块,所以可以包含。 总结步骤: 1. 引入Quartz的基本概念和作用。 2. 分步骤说明使用流程:配置调度器、定义任务、创建触发器、启动调度器。 3. 每个步骤中包含代码示例,并引用相关引用内容。 4. 生成相关问题,如配置、集群、持久化、异常处理等。 5. 确保引用标识正确放置,如任务类需要空构造函数引用[2],Job接口引用[3],集群节点引用[1]。</think>### Quartz 使用教程 Quartz 是一个开源的作业调度框架,用于在 Java 应用中管理定时任务。以下是其核心使用步骤: --- #### 1. **配置调度器** Quartz 的核心是 `Scheduler`,需通过工厂类创建并配置参数: ```java // 创建调度器工厂 SchedulerFactory schedulerFactory = new StdSchedulerFactory(); // 获取调度器实例 Scheduler scheduler = schedulerFactory.getScheduler(); ``` 若需集群配置,可在 `quartz.properties` 中定义节点属性[^1]。 --- #### 2. **定义任务类** 任务需实现 `org.quartz.Job` 接口,并满足以下条件: - 实现 `execute()` 方法,编写具体任务逻辑。 - 提供**公共空构造函数**(Quartz 反射实例化任务类时需要)[^2]。 ```java public class MyJob implements Job { public MyJob() {} // 必须的空构造函数 @Override public void execute(JobExecutionContext context) { System.out.println("任务执行中..."); } } ``` --- #### 3. **创建触发器** 触发器定义任务执行规则。例如,使用 `SimpleTrigger` 实现间隔触发: ```java // 每隔5秒执行一次,重复3次 Trigger trigger = TriggerBuilder.newTrigger() .withIdentity("trigger1") .startNow() .withSchedule(SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(5) .withRepeatCount(3)) .build(); ``` --- #### 4. **绑定任务与触发器并启动** 将任务和触发器注册到调度器中: ```java // 定义任务详情,关联 MyJob 类 JobDetail job = JobBuilder.newJob(MyJob.class) .withIdentity("job1") .build(); // 绑定任务和触发器 scheduler.scheduleJob(job, trigger); // 启动调度器 scheduler.start(); ``` --- ### 关键配置项 - **持久化**:通过 `JobStore` 配置将任务状态保存到数据库。 - **线程池**:在 `quartz.properties` 中调整线程数量以优化性能。 - **集群模式**:配置数据库持久化后,多个节点可自动协调任务[^1]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值