一、下面是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:jaxws="
http://cxf.apache.org/jaxws
"
xmlns:soap="
http://cxf.apache.org/bindings/soap
"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://cxf.apache.org/bindings/soap
http://cxf.apache.org/schemas/configuration/soap.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd
"
default-lazy-init="false">
<!-- 使用QuartzJobBean的定时器 -->
<bean id="usingQuartz" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass">
<!-- ftp上传job -->
<value>com.unistore.pay.ftp.MyTaskUsingQuartzJobBean</value>
</property>
</bean>
<bean id="usingbillQuartz" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass">
<!-- 生成话单job -->
<value>com.unistore.pay.ftp.GenerateBilInfoQuartz</value>
</property>
</bean>
<bean id="usingbfbillQuartz" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass">
<!-- 备份话单job -->
<value>com.unistore.pay.ftp.GenerateBFBilQuartz</value>
</property>
</bean>
<!-- ftp上传定时触发器 -->
<bean id="usingQuartzCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<ref bean="usingQuartz" />
</property>
<property name="cronExpression">
<value>40 * * * * ?</value>
<!--<value>0 30 01 * * ?</value> -->
</property>
</bean>
<!-- 中间账单生成定时触发器 -->
<bean id="usingbillQuartzCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<ref bean="usingbillQuartz" />
</property>
<property name="cronExpression">
<value>20 * * * * ?</value>
<!--<value>0 00 00 * * ?</value> -->
</property>
</bean>
<!-- 中间账单备份定时触发器 -->
<bean id="usingbfbillQuartzCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<ref bean="usingbfbillQuartz" />
</property>
<property name="cronExpression">
<value>59 * * * * ?</value>
<!--<value>0 30 05 * * ?</value> -->
</property>
</bean>
<!-- 启动定时器 -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean" lazy-init="false">
<property name="triggers">
<list>
<ref bean="usingQuartzCronTrigger" />
<ref bean="usingbillQuartzCronTrigger" />
<ref bean="usingbfbillQuartzCronTrigger" />
</list>
</property>
</bean>
</beans>
二、下面是关于每个类的说明(这里只是个demo,所以写法有点粗糙)
1、上传FTP的JobDetail类
package com.unistore.pay.ftp;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import com.enterprisedt.net.ftp.FTPException;
public class MyTaskUsingQuartzJobBean extends QuartzJobBean {
String dateTime =null;
String filepath=null;
// 该类FTPBiz的写法是重写了com.enterprisedt.net.ftp.FTPClient,请看下面该类的解释
FTPBiz ftpbiz=new FTPBiz();
Integer result=0;
/**
* 定时任务
* @return
*/
@Override
protected void executeInternal(JobExecutionContext arg0)
throws JobExecutionException {
filepath=ConstantParameter.FTPLOCALPATH+this.getSuccPayFile();
System.out.println(filepath);
File files=new File(filepath);
try {
result=ftpbiz.saveServer(files);
} catch (IOException e) {
result = CodeResource.FTP_CONNECT_FALSE;
} catch (FTPException e) {
result = CodeResource.FTP_CONNECT_FALSE;
}
System.out.println(result);
}
/**
* 转换时间格式
* @return
*/
public String getChangeTime(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
// 获取服务器的当前时间
dateTime = sdf.format(new Date(System.currentTimeMillis()));
return dateTime;
}
/**
* 获取成功交易的对账文件名称
* @return
*/
public String getSuccPayFile(){
dateTime=this.getChangeTime();
filepath=ConstantParameter.BUSINESSLOGO+"_"+dateTime+"_1.txt";
return filepath;
}
}
// 该类FTPBiz是重写了com.enterprisedt.net.ftp.FTPClient,区别不大,只是重新包装了自己的异常和业务实现
package com.unistore.pay.ftp;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.log4j.Logger;
import com.enterprisedt.net.ftp.FTPClient;
import com.enterprisedt.net.ftp.FTPException;
public class FTPBiz {
private static final Logger logger = Logger
.getLogger(FTPBiz.class);
private static final FTPBiz singleton = new FTPBiz();
// 获取FTP服务器联接
FtpVO ftpVO =null;
private FTPClient client = null;
// public FtpVO ftpVO = new FtpVO();
/**
* 获取单实例
*
* @return FtpBiz
*/
public static FTPBiz getInstance() {
return singleton;
}
public FTPBiz() {
}
/**
* 获取存在服务器的文件名 文件名+当前时间(yyyyMMdd)+文件类型(.txt)
*
* @param tfName
* @return
*/
public String changeFileName(String tfName) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
// 获取服务器的当前时间
String dateTime = sdf.format(new Date(System.currentTimeMillis()));
// 获取文件名的类型
String fileType = tfName.substring(tfName.lastIndexOf("."), tfName
.length());
return tfName.substring(0, tfName.lastIndexOf(".") > 110 - fileType
.length() ? 110 - fileType.length() : tfName.lastIndexOf("."))
+ dateTime + fileType;
}
/**
* 上传文件操作
*
* @param fileName
* String
* @param file
* FormFile
* @return
* @throws IOException
* @throws FTPException
* @throws FTPException
*/
public int saveServer(File file) throws IOException, FTPException {
int result = CodeResource.FTP_OPERATION_SUCCESS;
String fileName=file.getName();
MyFTPClient ftpClient = null;
// 参数校验,判断file 是否为空
if (null == file) {
result=CodeResource.FILE_ISNULL;
logger.debug("File is empty");
return result;
}
//文件是否存在
if (!file.exists()){
result=CodeResource.FILE_ISEXIST;
logger.debug("File does not exist");
//return result;
}
//文件是否是一个文件夹
if (!file.isFile()){
result=CodeResource.FILE_ISFILE;
logger.debug("Whether a file is a file folder");
return result;
}
//判断文件是否太大
long filesize=Long.parseLong(ConstantParameter.FTPFILEMAX);
if (file.length() > filesize) {
result=CodeResource.FILE_OVER;
logger.debug("File is too large");
return result;
}
try {
// FTP客户端对象
ftpClient = new MyFTPClient();
// 执行FTP连接初始化
ftpVO=new FtpVO();
//服务器IP
ftpVO.setServer(ConstantParameter.FTPSERVER);
//服务器端口
ftpVO.setPort(Integer.parseInt(ConstantParameter.FTPPORT));
//ftp服务器访问用户名
ftpVO.setUser(ConstantParameter.FTPUSER);
//ftp服务器密码
ftpVO.setPassword(ConstantParameter.FTPPASSWORD);
//ftp服务器文件存放路径
ftpVO.setServerPath(ConstantParameter.FTPSERVERPATH);
ftpClient.init(ftpVO.getServer(), ftpVO.getPort(), ftpVO.getUser(),
ftpVO.getPassword());
logger.info("FTP link successfully");
} catch (Exception fe) {
result = CodeResource.FTP_CONNECT_FALSE;
logger.info("FTP link failure");
return result;
}
// 判断该文件在ftp服务器上面是否已存在,若存在,则删除文件
try {
String b[] = ftpClient.dir(ConstantParameter.FTPSERVERPATH,fileName);
if (b != null && b.length != 0) {
ftpClient.delete(ConstantParameter.FTPSERVERPATH,fileName);
logger.info("File deleted successfully");
}
} catch (Exception e) {
result = CodeResource.FTP_CONNECT_FALSE;
logger.info("File deleted failure");
return result;
}
FileInputStream is = new FileInputStream(file);
// 将文件上传到FTP服务器
try {
ftpClient.put(ftpVO.getServerPath(),is,fileName);
}catch (IOException e) {
result = CodeResource.IO_CODE_ERROR;
logger.info("File upload successfully");
}
if (ftpClient != null) {
ftpClient.close();
logger.info("closed ftpserver");
}
// 返回成功标识
return result;
}
/**
* 删除文件操作
*
* @param tfName
* String
* @return int
* @throws IOException
* @throws FTPException
*/
public int deleteFtpFile(String fileName) throws Exception {
// 是否成功标识
int result = CodeResource.FTP_OPERATION_SUCCESS;
MyFTPClient ftpClient = null;
// 执行FTP连接初始化
try {
// FTP客户端对象
ftpClient = new MyFTPClient();
// 执行FTP连接初始化
ftpVO=new FtpVO();
ftpVO.setServer(ConstantParameter.FTPSERVER);
//服务器端口
ftpVO.setPort(Integer.parseInt(ConstantParameter.FTPPORT));
//ftp服务器访问用户名
ftpVO.setUser(ConstantParameter.FTPUSER);
//ftp服务器密码
ftpVO.setPassword(ConstantParameter.FTPPASSWORD);
//ftp服务器文件存放路径
ftpVO.setServerPath(ConstantParameter.FTPSERVERPATH);
ftpClient.init(ftpVO.getServer(), ftpVO.getPort(), ftpVO.getUser(),
ftpVO.getPassword());
// 判断文件是否存在
try {
String b[] = ftpClient.dir(ConstantParameter.FTPSERVERPATH,fileName);
if (b == null || b.length == 0) {
result = CodeResource.FTP_FILENULL;
return result;
} else {
ftpClient.delete(ConstantParameter.FTPSERVERPATH,fileName);
System.out.println("删除成功!");
}
} catch (Exception e) {
result = CodeResource.FTP_CONNECT_FALSE;
return result;
}
} catch (FTPException fe) {
result = CodeResource.FTP_OPERATION_FAILURE;
} finally {
if (ftpClient != null) {
ftpClient.close();
}
}
return result;
}
/**
* 编码转换
*
* @param fileName
* String
* @return String
*/
public String convert(String fileName) {
try {
byte bt[] = fileName.getBytes("iso-8859-1");
String vfName = new String(bt, "ISO-8859-1");
return vfName;
} catch (Exception e) {
return fileName;
}
}
}
2、从数据库读取数据,并生成话单文件的JobDetail类
package com.unistore.pay.ftp;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
import com.unistore.pay.service.IPayOptLogService;
import com.unistore.pay.utils.UtilDateTime;
public class GenerateBilInfoQuartz extends QuartzJobBean {
//读取数据库并生成话单的service
private IPayOptLogService payOptLogService;
/**
* 定时任务
* @return
*/
@Override
protected void executeInternal(JobExecutionContext arg0)
throws JobExecutionException {
this.getpaysucc();
}
/**
* 转换时间格式
* @return
*/
public String getChangeTime(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// 获取服务器的当前时间
String dateTime = sdf.format(new Date(System.currentTimeMillis()));
return dateTime;
}
/**
* 打印交易成功记录
* @return
*/
public void getpaysucc(){
ApplicationContext ctx=new ClassPathXmlApplicationContext("/applicationContext.xml");
payOptLogService = (IPayOptLogService) ctx.getBean("payOptLogService");
String datetime=this.getChangeTime();
Long createds=UtilDateTime.getTimetoss(datetime);
Long created=UtilDateTime.getTimetoss(datetime)-86400;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
// 获取服务器的当前时间
String dateTime = sdf.format(new Date(System.currentTimeMillis()));
String filepath=ConstantParameter.FTPLOCALPATH+ConstantParameter.BUSINESSLOGO+"_"+dateTime+"_1.txt";
boolean f=payOptLogService.selectBetweenBlock(5, created,createds,filepath);
System.out.println(f);
}
}
//读取数据库并生成话单的service
public class PayOptLogService implements IPayOptLogService {
private static final Logger logger = Logger
.getLogger(PayOptLogService.class);
// 日志操作Dao
private PayOptLogDao payOptLogDao;
/**
* 打印中间账户交易记录
* @param createds
* @param way
* @param created
* @return
*/
public boolean selectBetweenBlock(int way,long created,long createds,String filepath) {
// TODO Auto-generated method stub
boolean f=false;
Map map=new HashMap<Object,Object>();
if(way!=0){
map.put("way", way);
}
map.put("createds", createds);
map.put("created", created);
//数据库是mysql,持久层框架是ibatis
List<PayOptLog> list=payOptLogDao.find("selectBetweenBlock", map);
logger.debug("select success");
PrintWriter pw=null;
try {
File file=new File(filepath);
if(!file.exists())//如果文件不存在,则新建.
{
File parentDir=new File(file.getParent());
if(!parentDir.exists())//如果所在目录不存在,则新建.
parentDir.mkdirs();
file.createNewFile();
logger.debug("Successfully create the file");
}else{
logger.debug("File is exists");
return f;
}
pw = new PrintWriter( new FileWriter(filepath,true) );
} catch (IOException e) {
logger.debug("File printing failure");
e.printStackTrace();
}
//下面是生成话单文件
话单头:行数|总金额
话单体:
pw.println(list.size()+"|"+list.get(0).getTotalPrice());
for (PayOptLog payOptLog : list) {
payOptLog.setBusinessFoot(ConstantParameter.BUSINESSFOOT);
payOptLog.setParlogo(ConstantParameter.BUSINESSLOGO);
pw.println(payOptLog.getPayFloodId()+"|"+payOptLog.getOrderSn()+"|"+payOptLog.getBusinessFoot()+"|"+payOptLog.getPaytime()+"|"+payOptLog.getCount()+"|"+payOptLog.getParlogo()+"|"+payOptLog.getDescription());
logger.debug("File printing success");
pw.close();
f=true;
}
return f;
}
}
3、把话单临时生成的文件夹里面的话单文件移动到备份文件夹
package com.unistore.pay.ftp;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
public class GenerateBFBilQuartz extends QuartzJobBean {
String dateTime =null;
String filepath=null;
private static final Logger logger = Logger
.getLogger(GenerateBFBilQuartz.class);
/**
* 定时任务
* @return
*/
@Override
protected void executeInternal(JobExecutionContext arg0)
throws JobExecutionException {
filepath=ConstantParameter.FTPLOCALPATH+this.getSuccPayFile();
File dstFile = new File(filepath);
File upFile = new File(ConstantParameter.BFBUYPATH+this.getSuccPayFile());
try {
if(!upFile.exists())//如果文件不存在,则新建.
{
File parentDir=new File(upFile.getParent());
if(!parentDir.exists())//如果所在目录不存在,则新建.
parentDir.mkdirs();
upFile.createNewFile();
logger.debug("Successfully create the file");
}
FileUtils.copyFile(dstFile,upFile);
logger.info("Successfully bf the file");
if(dstFile.exists()){
dstFile.delete();
logger.debug("Successfully delete the file");
}
} catch (IOException e) {
logger.info("File bf failure");
e.printStackTrace();
}
}
/**
* 转换时间格式
* @return
*/
public String getChangeTime(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
// 获取服务器的当前时间
dateTime = sdf.format(new Date(System.currentTimeMillis()));
return dateTime;
}
/**
* 获取成功交易的对账文件名称
* @return
*/
public String getSuccPayFile(){
dateTime=this.getChangeTime();
filepath=ConstantParameter.BUSINESSLOGO+"_"+dateTime+"_1.txt";
return filepath;
}
}
//后续将继续完善 ^_^
版权声明:本文为博主原创文章,未经博主允许不得转载。