2.HuPaymentTask.java
一个定时任务类,WeatherTask.java与这个类似,就不写了
package
cn.abc.timertask.biz.fight.huPayment;
public class HuPaymentTask {
public void work() {
System.out.println("这里写这个定时任务需要执行的操作代码");
}
}
3.MethodTimeAdvice.java
切面类,其中加入了将拦截的内容加入到数据库的代码,如果不需要可以相应删掉
package cn.abc.timertask.core.common.taskManager;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.StopWatch;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.ThrowsAdvice;
import
cn.abc.timertask.core.common.taskManager.po.TaskDetail;
public class MethodTimeAdvice implements MethodInterceptor
{
protected final Log log =
LogFactory.getLog(MethodTimeAdvice.class);
public Object invoke(MethodInvocation invocation) {
Object[] object = invocation.getArguments();
ScheduleInfoManager scheduleInfoManager = new
ScheduleInfoManager();//这个类封装了对数据库的增删改查操作
TaskDetail taskDetail = new TaskDetail();//这是一个实体
// 用 commons-lang 提供的 StopWatch 计时,Spring 也提供了一个
StopWatch
StopWatch clock = new StopWatch();
clock.start(); // 计时开始
String beforeTime = new SimpleDateFormat("yyyy-MM-dd
HH:mm:ss:SSS").format(new Date());
System.out.println("启动时间:"+ beforeTime);
taskDetail.setTask_detail_startdate(beforeTime);
Object result = null;
try {
result = invocation.proceed();
System.out.println(result);
taskDetail.setTask_detail_isexception("0");
} catch (Exception e) {
// TODO: handle exception
System.out.println("捕获的异常:"+e.getMessage());
String exceptionTime = new SimpleDateFormat("yyyy-MM-dd
HH:mm:ss:SSS").format(new Date());
taskDetail.setTask_detail_isexception("1");
taskDetail.setTask_detail_exceptiondesc(e.getMessage());
taskDetail.setTask_detail_executedate(exceptionTime);
}finally{
clock.stop(); // 切面结束
String endTime = new SimpleDateFormat("yyyy-MM-dd
HH:mm:ss:SSS").format(new Date());
System.out.println("结束时间:"+ endTime);
taskDetail.setTask_detail_enddate(endTime);
// 方法参数类型,转换成简单类型
Class[] params =
invocation.getMethod().getParameterTypes();
String[] simpleParams = new String[params.length];
for (int i = 0; i < params.length; i++) {
simpleParams[i] = params[i].getSimpleName();
}
System.out.println("结束时间:" + clock.getTime() + " ms");
taskDetail.setTask_detail_executedate(clock.getTime() + "
ms");
System.out.println("每次执行时间:" + clock.getTime() + " ms");
System.out.println("操作类(包名+类名+方法名+(参数)): ["
+ invocation.getThis().getClass().getName() + "."
+ invocation.getMethod().getName() + "("
+ StringUtils.join(simpleParams, ",") + ")] ");
System.out.println(result);
//这里将拦截的数据插入的数据库
scheduleInfoManager.insertTaskDetail(taskDetail);
return result;
}
}
}