Quartz使用

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()+"*****");
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值