基于Java反射的定时任务设计

定时任务调度
复制代码
/**

  • 执行通用任务
    /
    public void doTaskList() {
    List taskList = taskMapper.selectTaskList();
    if (CollectionUtils.isEmpty(taskList)) {
    return;
    }
    for (Task task : taskList) {
    try {
    Integer retryTimes = task.getRetryTimes();
    if (retryTimes == 1) {
    Date updateTime = task.getGmtModified();
    // 第一次重试,执行时间和上次时间间隔至少5分钟
    if (updateTime.getTime() + 1000 * 60 * 5 > System.currentTimeMillis()) {
    continue;
    }
    }
    if (retryTimes == 2) {
    Date updateTime = task.getGmtModified();
    // 第二次重试,执行时间和上次时间间隔至少30分钟
    if (updateTime.getTime() + 1000 * 60 * 30 > System.currentTimeMillis()) {
    continue;
    }
    }
    service.doTaskExec(task);
    } catch (Exception e) {
    // 执行失败发送提醒邮件
    }
    }
    }
    复制代码
    反射执行
    复制代码
    /
    *

  • 通用任务执行

  • @param task 待执行的任务
    */
    public void doTaskExec(Task task) throws ClassNotFoundException {
    String execClass = task.getExecClass();
    String execMethod = task.getExecMethod();
    String execParam = task.getExecParam();

    Class<?> clazz = Class.forName(execClass);
    Object object = ApplicationContextUtil.getBean(clazz);
    Method[] methods = clazz.getMethods();
    for (Method method : methods) {
    if (!method.getName().equals(execMethod)) {
    continue;
    }
    Class<?>[] paramTypes = method.getParameterTypes();
    Object[] objectValue = new Object[paramTypes.length];
    for (int i = 0; i < paramTypes.length; i++) {
    objectValue[i] = JSON.parseObject(execParam, paramTypes[i]);
    }
    Object execResult;
    try {
    execResult = reflection(object, clazz, execMethod, paramTypes, objectValue);
    } catch (Exception e) {
    log.error(“外部接口返回异常:”, e);
    processFailureExecResult(task, e.getMessage());
    return;
    }
    processExecResult(task, JSON.toJSONString(execResult));
    }
    }
    亚马逊测评 www.yisuping.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值