利用反射实现定时任务工具类

利用反射实现定时任务工具类

最近项目需要做一个定时获取信息的一个功能,我起先想着用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});
	}
}

敲代码无非是为了开心嘛!!嘿嘿嘿
我们的目标:改变世界!哈哈哈

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值