1. 程式人生 > >基於quartz的定時任務

基於quartz的定時任務

1,配置檔案

<?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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="initDataService" class="com.maxxipoint.exchange.manager.filter.service.initDataService"></bean>

    <!--自動註冊集享卡會員定時任務-->
    <bean id="autoRegistJXKMember" class="com.maxxipoint.exchange.manager.manage.AutoRegisterJXKMember">
        <constructor-arg index="0"><value>${register.mutexjob.exeip}</value></constructor-arg>
        <!-- <constructor-arg index="0"><value>10.40.37.13</value></constructor-arg> -->
    </bean>

    <!-- 配置目標任務要執行的方法 -->
    <bean id="autoRegistJXKTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject">
            <ref bean="autoRegistJXKMember"/>
        </property>
        <property name="targetMethod">
            <value>executeRegister</value>
        </property>
        <property name="concurrent" value="false"/>
    </bean>
    <!--配置定時任務相關屬性,執行時間-->
    <bean id="autoRegistJXKTaskTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail">
            <ref bean="autoRegistJXKTask"/>
        </property>
        <!--cron表示式 -->
        <property name="cronExpression">
            <!--每5分鐘執行一次,第1分鐘開始 —>
            <!—- 此處修改執行的時間 -->
            <!--<value>59 59 23 * * ?</value>-->
            <value>0 0/2 * * * ?</value>
            <!-- <value>0 0 17 * * ?</value> -->
        </property>
        <property name="misfireInstruction" value="2"/>
    </bean>

    <!--總管理類,定時任務啟動入口,沒有這個配置,任務不會自動執行-->
    <bean id="registerStartQuartz" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="autoStartup" value="true"/>
        <property name="triggers">
            <list>
                <ref bean="autoRegistJXKTaskTrigger"/>
            </list>
        </property>
    </bean>

2,定時任務父類抽象類,用於多個定時任務分別執行

package com.maxxipoint.exchange.manager;

import com.communion.server.framework.protocols.respones.DataResult;
import com.maxxipoint.exchange.manager.bean.ResponseBean;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 互斥定時任務抽象介面
 * 
 * @author samyin
 *
 */
public abstract class AbstractMutexJobIP {
	
	protected String exeServiceIp;
	
	public AbstractMutexJobIP(String exeServiceIp){
		this.exeServiceIp = exeServiceIp;
	}
	
	public String getExeServiceIp() {
		return exeServiceIp;
	}
	public void setExeServiceIp(String exeServiceIp) {
		this.exeServiceIp = exeServiceIp;
		this.exeServiceIp.trim();
	}

	public void execute() {
		try {
			InetAddress address = InetAddress.getLocalHost();
//			String hostName = address.getHostName();
//			String canonicalHostName = address.getCanonicalHostName();//主機別名
			String ip = address.getHostAddress();//獲取IP地址
			
//			System.out.println( "hostName=" + hostName + 
//			"; 主機別名=" + canonicalHostName
//					+ ";ip=" + ip);
			
			ip = ip.trim();
			/*if(ip.toLowerCase().equals(exeServiceIp.toLowerCase()) == false){
				return ;
			}*/
			boolean flag = false;
			String[] executeips = exeServiceIp.toLowerCase().split(",");
			for(String executeip:executeips){
				if(executeip.equals(ip.toLowerCase())){
					flag = true;
				}
			}
			if(!flag){
				return ;
			}
			doExecute();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}

	}

	public void executeRegister() {
		try {
			InetAddress address = InetAddress.getLocalHost();
//			String hostName = address.getHostName();
//			String canonicalHostName = address.getCanonicalHostName();//主機別名
			String ip = address.getHostAddress();//獲取IP地址

//			System.out.println( "hostName=" + hostName +
//			"; 主機別名=" + canonicalHostName
//					+ ";ip=" + ip);

			ip = ip.trim();
			/*if(ip.toLowerCase().equals(exeServiceIp.toLowerCase()) == false){
				return ;
			}*/
			boolean flag = false;
			String[] executeips = exeServiceIp.toLowerCase().split(",");
			for(String executeip:executeips){
				if(executeip.equals(ip.toLowerCase())){
					flag = true;
				}
			}
			if(!flag){
				return ;
			}
			doExecuteRegister();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}

	}
	protected abstract DataResult<ResponseBean> doExecuteRegister();
}

3,定時任務具體實現類

package com.maxxipoint.exchange.manager.manage;


import com.baidu.disconf.client.usertools.DisconfDataGetter;
import com.communion.server.framework.protocols.respones.DataResult;

import com.maxxipoint.exchange.dao.entity.*;
import com.maxxipoint.exchange.dao.mapper.FileRegisterDetailMapper;
import com.maxxipoint.exchange.dao.mapper.FileRegisterMapper;
import com.maxxipoint.exchange.manager.AbstractMutexJobIP;
import com.maxxipoint.exchange.manager.bean.ResponseBean;
import com.maxxipoint.exchange.manager.service.IRegisterMemberService;
import com.maxxipoint.exchange.manager.util.ResultEnum;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class AutoRegisterJXKMember extends AbstractMutexJobIP {
    private final static Logger log = LogManager.getLogger(AutoRegisterJXKMember.class);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
    DecimalFormat df = new DecimalFormat ("#,#");

    @Autowired
    private FileRegisterMapper fileRegisterMapper;

    @Autowired
    private FileRegisterDetailMapper fileRegisterDetailMapper;

    @Autowired
    private IRegisterMemberService registerMemberService;

    private static String SEPARATOR = System.getProperty("file.separator");
    private static String PATH ;
    private static String IP;
    private static String PORT;
    private static String USERNAME;
    private static String PASSWORD;
    private static String REGISTFILEPATH;

    static{
        PATH = "/data" + SEPARATOR + "files" + SEPARATOR+ "csv" + SEPARATOR + "export" + SEPARATOR;
//		PATH = "D:/";

        DisconfDataGetter disconfDataGetter = new DisconfDataGetter();
        Map<String,Object> map = disconfDataGetter.getByFile("application.properties");
        IP=String.valueOf(map.get("autoReconciliation.ftp.ip"));
        PORT=String.valueOf(map.get("autoReconciliation.ftp.port"));
        USERNAME=String.valueOf(map.get("autoReconciliation.ftp.username"));
        PASSWORD=String.valueOf(map.get("autoReconciliation.ftp.password"));
        REGISTFILEPATH=String.valueOf(map.get("autoReconciliation.ftp.registJXKFilePath"));
    }

    public AutoRegisterJXKMember(String exeServiceIp) {
        super(exeServiceIp);
    }

    @Override
    protected void doExecute() {

    }

//    @Transactional
    @Override
    protected DataResult<ResponseBean> doExecuteRegister() {
        //每日生成當天的檔名 格式:merchId_date_registerFTP
        //TODO:生成每日的檔名,儲存到資料庫中。
        DataResult<ResponseBean> dataResult = new DataResult<ResponseBean>();
        try{
            Map<String,Object> busMap = new HashMap<String,Object>();
            busMap.put("supportFtpFile",1);
            //1.DB讀取FTP檔案的商家列表
            List<BusinessInfo> businessInfoList = registerMemberService.selectBusinessByMap(busMap);
            if( null == businessInfoList || businessInfoList.size() == 0){
                log.info("需要上傳FTP的商家列表為空");
                dataResult.setCode(ResultEnum.BUSINESS_DATA_EMPTY.getCode());
                dataResult.setMsg(ResultEnum.BUSINESS_DATA_EMPTY.getMsg());
                return dataResult;
            }
            //2.遍歷各個商家,根據定義日期格式,生成規則為:merch_id+date+inx
            for (BusinessInfo businessInfo:businessInfoList){
                //將每日生成的檔名,新建檔案記錄
                FileRegister fileRegister = new FileRegister();
                String merch_id = businessInfo.getMerchId();
                String registeDate = sdf1.format(new Date());
                String fileName = merch_id +"_" + registeDate +"_"+ "A";
                fileRegister.setMerchId(merch_id);
                fileRegister.setRegistDate(new Date());
                fileRegister.setFileName(fileName);
                fileRegister.setCreateTime(new Date());
                fileRegister.setUpdateTime(new Date());
                int i = registerMemberService.insertBusiness(fileRegister);
                log.info("每日生成"+merch_id+"的商家的檔名結果:"+i);
            }
            //3.查詢需要去FTP拉取檔案的記錄
            byte fileReadStatus = 0;
            List<FileRegister> fileRegisterList = registerMemberService.selectFileByFileReadStatus(fileReadStatus);
            if(null == fileRegisterList || fileRegisterList.size() == 0){
                log.info("需要到FTP拉取的檔案列表為空");
                dataResult.setCode(ResultEnum.FILE_DATA_EMPTY.getCode());
                dataResult.setMsg(ResultEnum.FILE_DATA_EMPTY.getMsg());
                return dataResult;
            }

            for( FileRegister fileRegister : fileRegisterList){
                byte flag = 0;
                //開始執行讀取FTP及自動註冊邏輯
                dataResult = registerMemberService.doExecuteReal(fileRegister);

                //查詢新增資料,如有異常,則將檔案的狀態改為異常狀態,0 待讀,1 讀取完成, 2讀取有異常
                Map<String,Object> fileDetailMap = new HashMap<String,Object>();
                fileDetailMap.put("fileRegisterId",fileRegister.getId());
                fileDetailMap.put("memberRegistStatus",2);
                List<FileRegisterDetail> fileRegisterDetailList = registerMemberService.selectFileDetailMap(fileDetailMap);
                if(fileRegisterDetailList != null && fileRegisterDetailList.size() >0){
                    flag = 2;
                }else {
                    if(dataResult.getCode().equals("00")){
                        flag = 1;
                    }
                }
                fileRegister.setFileReadStatus(flag);
                //遍歷完當前檔案,修改檔案狀態
                registerMemberService.updateFilereadStatus(fileRegister);
            }

        }catch (Exception e){
            e.printStackTrace();
            dataResult.setCode(ResultEnum.SYSTEM_ERROR.getCode());
            dataResult.setMsg(e.getMessage());
            return dataResult;
        }
        return dataResult;
    }

}