利用反射实现定时任务工具类
最近项目需要做一个定时获取信息的一个功能,我起先想着用Timer类一步到位做好。但老大发话说,不能这样写,必须让我写个封装的工具类,业务逻辑放在service层,这样一步到位写虽快,但是不觉得代码的耦合性很高吗?
感觉老大说的很有道理!!!!
懒得写注释了,基本反射加Timer而已。反正也只是写篇博客记录一下,爱看不看
package com.tom.utils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class goldInformation{
/**
*
* @param time 定时时间
* @param className 类名
* @param methodName 方法名
* @param period 任务循环时间
* @param methodParameter 传入的参数
* @throws Exception
*/
public static void timer(String time,String className,String methodName,long period,Object...methodParameter) throws Exception {
Class<?> classType = Class.forName(className);
Object objectClass = classType.newInstance();
Method[] declaredMethods = objectClass.getClass().getDeclaredMethods();
Class<?>[] a = null;
for (int i = 0; i < declaredMethods.length; i++) {
if(declaredMethods[i].getName().equals(methodName)) {
Class<?>[] parameterTypes = declaredMethods[i].getParameterTypes();
a = parameterTypes;
}
}
Method method = objectClass.getClass().getDeclaredMethod(methodName,a);
SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(time);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
try {
method.invoke(objectClass, methodParameter);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
}, date, period);
}
public static void main(String[] args) throws Exception {
timer("2018-12-21 11:20:20","com.tom.utils.Test","test",2000,new Object[] {"hello","spring","!",123});
}
}
敲代码无非是为了开心嘛!!嘿嘿嘿
我们的目标:改变世界!哈哈哈