package com.usoftchina.uas.office.util;

import java.util.concurrent.Callable;

/**
 * @author yingp
 * @date 2020/2/18
 */
public class Try {
    /**
     * 多次尝试执行一段代码，直到拿到结果
     *
     * @param callable
     * @param times
     * @param <R>
     * @return
     * @throws Exception
     */
    public static <R> R call(Callable<R> callable, int times) {
        for (int i = 0; i < times; i++) {
            try {
                R result = callable.call();
                if (null != result) {
                    return result;
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                return null;
            }
        }
        return null;
    }
}
