RunHelper.java 1.36 KB
package com.yanzuoguang.util.helper;


import com.yanzuoguang.util.thread.ThreadHelper;

/**
 * 重复执行工具类
 *
 * @author 颜佐光
 */
public class RunHelper {

    /**
     * 执行次数
     */
    public final static int REQ_SIZE = 3;

    /**
     * 执行次数,并且获取最后一次的异常
     *
     * @param tag   标记
     * @param run   需要执行的函数
     * @param sleep 需要沉睡的时间
     */
    public static void run(String tag, Runnable run, int sleep) {
        run(tag, run, sleep, REQ_SIZE);
    }

    /**
     * 执行次数,并且获取最后一次的异常
     *
     * @param tag   标记
     * @param run   需要执行的函数
     * @param sleep 需要沉睡的时间
     * @param size  需要执行的次数
     */
    public static void run(String tag, Runnable run, int sleep, int size) {
        Exception ex = null;
        for (int i = 0; i < size; i++) {
            try {
                run.run();
                ex = null;
                break;
            } catch (Exception e) {
                if (i < size) {
                    // 间隔100ms,防止服务器重启时请求失败
                    ThreadHelper.sleep(sleep);
                }
                ex = e;
            }
        }
        if (ex != null) {
            throw new RuntimeException(tag + ex.getMessage(), ex);
        }
    }
}