RunHelper.java 1.42 KB
Newer Older
yanzg's avatar
yanzg committed
1 2 3
package com.yanzuoguang.util.helper;


gongzuquan's avatar
gongzuquan committed
4
import com.yanzuoguang.util.YzgError;
yanzg's avatar
yanzg committed
5
import com.yanzuoguang.util.thread.ThreadHelper;
yanzg's avatar
yanzg committed
6 7 8

/**
 * 重复执行工具类
yanzg's avatar
yanzg committed
9
 *
yanzg's avatar
yanzg committed
10
 * @author 颜佐光
yanzg's avatar
yanzg committed
11 12 13 14 15 16
 */
public class RunHelper {

    /**
     * 执行次数
     */
yanzg's avatar
yanzg committed
17
    public final static int REQ_SIZE = 3;
yanzg's avatar
yanzg committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

    /**
     * 执行次数,并且获取最后一次的异常
     *
     * @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) {
yanzg's avatar
yanzg committed
39
        RuntimeException ex = null;
yanzg's avatar
yanzg committed
40 41 42 43 44
        for (int i = 0; i < size; i++) {
            try {
                run.run();
                ex = null;
                break;
yanzg's avatar
yanzg committed
45
            } catch (RuntimeException e) {
yanzg's avatar
yanzg committed
46
                if (i < size) {
yanzg's avatar
yanzg committed
47 48
                    // 间隔100ms,防止服务器重启时请求失败
                    ThreadHelper.sleep(sleep);
yanzg's avatar
yanzg committed
49 50 51 52 53
                }
                ex = e;
            }
        }
        if (ex != null) {
yanzg's avatar
yanzg committed
54
            throw YzgError.getRuntimeException(ex, "049", tag, ex.getMessage());
yanzg's avatar
yanzg committed
55 56 57
        }
    }
}